沃梦达 / 编程问答 / php问题 / 正文

如何合并两个 Eloquent 集合?

How to Merge Two Eloquent Collections?(如何合并两个 Eloquent 集合?)

本文介绍了如何合并两个 Eloquent 集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题表和一个标签表.我想从给定问题的标签中获取所有问题.因此,例如,我可能将标签旅行"、火车"和文化"附加到给定的问题.我希望能够获取这三个标签的所有问题.看起来棘手的是,问题和标签的关系在 Eloquent 中是多对多的,定义为belongsToMany.

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 "Culture" attached to a given question. I want to be able to fetch all questions for those three tags. The tricky, so it seems, is that questions and tags relationship is a many-to-many defined in Eloquent as belongsToMany.

我想尝试合并问题集合如下:

I thought about trying to merge the questions Collections as below:

foreach ($question->tags as $tag) {
    if (!isset($related)) {
        $related = $tag->questions;
    } else {
        $related->merge($tag->questions);
    }
}

虽然它似乎不起作用.似乎没有合并任何东西.我是否正确地尝试了这个?另外,是否有更好的方法在 Eloquent 中以多对多关系获取一行行?

It doesn't seem to work though. Doesn't seem to merge anything. Am I attempting this correctly? Also, is there perhaps a better way to fetch a row of rows in a many-to-many relationship in Eloquent?

推荐答案

merge 方法返回的是合并后的集合,不会对原集合进行变异,因此需要做如下操作

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

这篇关于如何合并两个 Eloquent 集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何合并两个 Eloquent 集合?

基础教程推荐