XF 2.1 Using finder to create an object with order same as array.

AndyB

Well-known member
I have an array called $threadIds.

PHP:
Array
(
    [0] => 271
    [1] => 166
    [2] => 169
    [3] => 140
    [4] => 367
    [5] => 566
    [6] => 120
)

The values are thread_id's.

I would like to create an object using the finder system and keep the same order as the $threadIds array. I realize I can add a ->order to the finder, but I would like the order in which the array is in.

This example works but the $similarThreads object is not in the same order as $threadIds array.

PHP:
foreach ($threadIds AS $threadId)
{
    $conditions[] = ['thread_id', $threadId];
}

$finder = \XF::finder('XF:Thread');
$similarThreads = $finder
    ->whereOr($conditions)
    ->fetch();

How can I create a $similarThreads object which will have the same order as the $threadIds array?

Thank you.
 
Just sort the collection after fetching: $similarThreads->sortByList($threadIds);

Also, you can simplify your conditional logic: $finder->whereIds($threadIds);
 
Thank you, Jeremy.

Here's what I have now:

PHP:
$finder = \XF::finder('XF:Thread');
$similarThreads = $finder->whereIds($threadIds);
        
$similarThreads->sortByList($threadIds);

Unfortunately I get this error:

Error: Call to undefined method XF\Finder\Thread::sortByList() in src/addons/Andy/SimilarThreads/Repository/SimilarThreads.php at line 1882
 
You would still need to call fetch() on the finder to get a collection. Also, collections are immutable so you need to re-capture the result of the sort (or chain the method after calling fetch).

PHP:
$finder = \XF::finder('XF:Thread')
    ->whereIds($threadIds);
$similarThreads = $finder->fetch();
$similarThreads = $similarThreads->sortByList($threadIds);
 
Top Bottom