如何合并两个雄辩的藏品? [英] How to merge two eloquent collections?

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

问题描述

我有一个问题表和一个标签表。我想从给定问题的标签中获取所有问题。所以,例如,我可以在给定的问题上附上标签旅行,火车和文化。我想要获取这三个标签的所有问题。似乎很棘手的是,问题和标签的关系是一个多对多的定义,在雄辩中被称为belongsToMany。



我想到了合并问题集如下:

  foreach($ question->标签为$标签){
if(!isset($相关)){
$ related = $ tag->问题;
} else {
$ related-> merge($ tag-> questions);
}
}

它似乎不起作用。似乎没有合并任何东西。我正在尝试这个吗?另外,有没有更好的方式来获取一些在多对多关系中排列的行列?

解决方案

合并方法返回合并集合,它不会将其合并到当前对象中,因此您需要执行以下

  $ original = new Collection(['foo']); 

$ latest = new Collection(['bar']);

$ merged = $ original-> merge($ latest); //包含foo和bar。

将示例应用于代码

  $ related = new Collection(); 

foreach($ question->标签为$标签)
{
$ related = $ related-> merge($ tag-> questions);
}


I have a questions table, and a tags table. I want to fetch all questions from tags of a given questions. 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);
    }
}

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

解决方案

The merge method returns the merged collection, it doesn't merge it into the current object, 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);
}

这篇关于如何合并两个雄辩的藏品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆