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

Asked

Viewed 79 times

0

I am with the ids returned from an immense query to bring the posts with a search term... Already working bring the posts through the Model by the selected IDS but it always brings sorted by ID and what I need is to sort by date... In the huge query I did, I already bring the ID’s sorted correctly but how much I use the model to search for the IDS, it clutters and brings ordered by the ID... Example of the code:

$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 seeking the IDS in the order I report, it searches in the ordered by the ID...

  • You tried to order using Post::find($postIds)->orderBy('data'); ?

  • Yes! The answer is just below... I ended up implementing in the hand... I saw in the github of the own one.

2 answers

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();
  • Simple and efficient(Opens only a single connection to the database).

0


I was able to sort it this way:

$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));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.