問題描述
我有一個問題表和一個標簽表.我想從給定問題的標簽中獲取所有問題.因此,例如,我可能將標簽旅行"、火車"和文化"附加到給定的問題.我希望能夠獲取這三個標簽的所有問題.看起來棘手的是,問題和標簽的關系在 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 集合?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!