如何合并两个雄辩的藏品? [英] How to merge two eloquent collections?
问题描述
我想到了合并问题集如下:
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屋!