I am working on a Laravel project where I have an array of article IDs, and I need to retrieve multiple records from the database for the same ID. However, when I use Eloquent, I only get one result even if the same ID appears multiple times in my array.
Here’s an example of the array:
$articleIds = [5, 5, 5];
$articles = Article::whereIn('id', $articleIds)->get();
The result I’m getting is only one record, but I expect to get multiple records since the same ID is repeated in the array.
How can I modify my Eloquent query to retrieve multiple records for the same ID?
I have also tried the below from another stack answer
Article::findMany($all_ids)->keyBy('id');
$blocks = array_map(function ($id) use ($all_record) {
return $all_record[$id];
}, $all_ids);
I can get the result using a loop but I do not want that result I want an eloquent or query (DB) way result.
2
Answers
A very rough way (as @PsyLogic mentioned) would be to just loop over the array and make a separate query for every ID:
While this approach does "work", It has the potential to cause some serious performance issues when given a large array of IDs.
What I can suggest is the UNION ALL