【问题标题】:Eloquent merge() is not merging as expected when fetching data from one column从一列获取数据时,Eloquent merge() 未按预期合并
【发布时间】:2016-10-09 02:58:09
【问题描述】:

我正在使用 Eloquent 的 ->merge() method。当您仅通过->get() 获取收藏集时,它看起来效果很好。

但是,当我添加select('some_column') 时,生成的集合出现了意外的结果。

例如我得到以下三个集合:

$collection_1 = Model_1 ::select('column')->whereNotNull('column2')->distinct()->get();
$collection_2 = Model_2 ::select('column')->whereNotNull('column2')->distinct()->get();
$collection_3 = Model_3 ::select('column')->whereNotNull('column2')->distinct()->get();

$options = $collection_1->merge($collection_2)->merge($collection_3);

在选项中,我只得到一个值,而不是预期的所有值。

对于$collection_1->count(),我得到了 10 条记录。 对于$collection_2->count(),我得到 8 条记录。 对于$collection_3->count(),我得到了 12 条记录。

但在生成的$options->count()(并使用merge())中,我只得到一条记录!!!

我错过了什么?

可能的解决方案

in this answer 所述,我使用->lists() 而不是->get()

这就是我所拥有的:

 $collection_1 = Model_1 ::whereNotNull('column2')->distinct()->lists('column');
 $collection_2 = Model_2 ::whereNotNull('column2')->distinct()->lists('column');
 $collection_3 = Model_3 ::whereNotNull('column2')->distinct()->lists('column');

 $options = $collection_1->merge($collection_2)->merge($collection_3);
 $options = $options->unique()->sort();

到目前为止,这就是诀窍☻

【问题讨论】:

  • 你能在第一种情况下dd()$options 的输出(当只有一条记录时)。

标签: merge eloquent


【解决方案1】:
Eloquent 集合的

merge() 方法使用模型的主键来区分模型实例。由于您仅获取不是主键的单个列,因此主键为空,并且 Collection 事物所有对象都只是同一对象的副本。

将主键列添加到传递给 select() 的列列表中,以便主键值可用并且合并可以正常工作。

【讨论】:

    猜你喜欢
    • 2021-09-27
    • 2015-11-08
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    相关资源
    最近更新 更多