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 ☻