How to Merge Two Eloquent Collections?(如何合并两个 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 集合?
基础教程推荐
- HTTP 与 FTP 上传 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01