How to bring Model by IDS and order at the same time

0

I have the ids returned from an immense query to bring the posts with a searched term ... It is already working to bring the posts through the Model by the selected IDS but it always brings by ID and what I need to order by date ... In the huge query I've done, I already have the IDs sorted correctly, but when I use the IDS lookup template, it gets cluttered and sorted by ID ... Code example:

$terms = explode(' ', Input::get('search'));
$results = 
DB::select(
    DB::raw($this->getSearchQuery($terms))
);

$postIds = [];
foreach ($results as $result) {
    array_push($postIds, $result->id);
}

$posts = Post::find($postIds);

The problem is in the last line that instead of looking for the IDS in the order that I inform, it searches in the ordered by ID ...

    
asked by anonymous 11.07.2014 / 22:52

2 answers

0

I was able to sort as follows:

$postIds = [];
foreach ($results as $result) {
    array_push($postIds, $result->id);
}

$posts = Post::find($postIds);

$sorted = array_flip($postIds);

foreach ($posts as $post) $sorted[$post->id] = $post;
$sorted = Collection::make(array_values($sorted));
    
12.07.2014 / 23:59
1

Let's say you have a list of ids in array format:

$ids = [1, 2, 8, 15, 78];

$posts = Post::whereIn($ids)->orderBy('created_at', 'desc')->get();
    
19.07.2014 / 13:29