1

I am using Eloquent's ->merge() method. It looks it works well when you only get collections through ->get() only.

However, when I add select('some_column'), the resulting collection has unexpected results.

For example, I get the following three collections:

$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);

In the options, I only get one value, and not all the values as expected.

For the $collection_1->count() I get 10 records. For the $collection_2->count() I get 8 records. For the $collection_3->count() I get 12 records.

But in the resulting $options->count() (and using merge()) I only get one record!!!

What am I missing?

Possible solution

I have used ->lists() instead of ->get() as stated in this answer.

So this is what I've got:

 $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();

And that made the trick so far ☻

Community
  • 1
  • 1
Pathros
  • 10,042
  • 20
  • 90
  • 156
  • Can you `dd()` the output of the `$options` in the first case (when there's only 1 record). – Vucko Jun 08 '16 at 18:34

1 Answers1

0

merge() method of Eloquent collection uses model's primary key to differentiate between model instances. As you're fetching only a single column that is not the primary key, the primary key is empty and Collection things all objects are just copies of the same object.

Add primary key column to the list of columns passed to select() so that primary key value is available and merging can work properly.

jedrzej.kurylo
  • 39,591
  • 9
  • 98
  • 107