如何合并两个 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 集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?(警告:mysqli_query() 需要至少 2 个参数,1 个给定.什么?)
INSERT query produces quot;Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean givenquot;(INSERT 查询产生“警告:mysqli_num_rows() 期望参数 1 为 mysqli_result,给出布尔值;)
prepared statements - are they necessary(准备好的陈述 - 它们是否必要)
Do I need to escape my variables if I use MySQLi prepared statements?(如果我使用 MySQLi 准备好的语句,是否需要转义我的变量?)
Properly Escaping with MySQLI | query over prepared statements(使用 MySQLI 正确转义 |查询准备好的语句)
Is it possible to use mysqli_fetch_object with a prepared statement(是否可以将 mysqli_fetch_object 与准备好的语句一起使用)