How to Merge Two Eloquent Collections?

后端 未结 6 803
梦如初夏
梦如初夏 2020-11-28 08:30

I have a questions table and a tags table. I want to fetch all questions from tags of a given question. So, for example, I may have the tags \"Travel,\" \"Trains\" and \"Cul

6条回答
  •  旧巷少年郎
    2020-11-28 09:06

    The merge method returns the merged collection, it doesn't mutate the original collection, thus you need to do the following

    $original = new Collection(['foo']);
    
    $latest = new Collection(['bar']);
    
    $merged = $original->merge($latest); // Contains foo and bar.
    

    Applying the example to your code

    $related = new Collection();
    
    foreach ($question->tags as $tag)
    {
        $related = $related->merge($tag->questions);
    }
    

提交回复
热议问题