skip to Main Content

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


  1. A very rough way (as @PsyLogic mentioned) would be to just loop over the array and make a separate query for every ID:

    $articleIds = [5, 5, 5];
    $articles = [];
    
    foreach ($articleIds as $articleId) {
        $articles[] = Article::where('id', $articleId)->first();
    }
    

    While this approach does "work", It has the potential to cause some serious performance issues when given a large array of IDs.

    Login or Signup to reply.
  2. What I can suggest is the UNION ALL

    if(count($articlesId) === 1){
     DB::table('articles')->where('id', $articlesId[0]);
    
    }else{
    
    $firstId = $articlesId[0];
    array_shift($articlesId)
    
    $articlesQuery = DB::table('articles')
        ->where('id',$firstId);
    
    foreach ($articlesId as $id) {
        $articlesQuery->unionAll(
            DB::table('articles')
            ->where('id', $id)
        );
    }
     
    $articles = $articlesQuery->get();
    
    
    }
    
    SELECT * FROM articles WHERE id = 1
    UNION ALL
    SELECT * FROM articles WHERE id = 1
    UNION ALL
    SELECT * FROM articles WHERE id = 1
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search