Reputation:
I am trying to display buildings and circuits in list (only 3 in total, sorted by the column "updated_at"). The problem is that they are not in the same table. I have a table circuits
and a table buildings
.
I tried to do this:
$buildings = Building::published()->limit(3)->get();
$circuits = Circuit::published()->limit(3)->get();
$merged = $buildings->merge($circuits);
$this->data['buildingsAndCircuits'] = $merged->all();
I get everything right when I'm doing my var_dump and I know how to access the data when I do a foreach. But that does not do what I want.
I would like to sort them (by updated_at
) and have only three and not six.
Is there a way to do that?
I tried to make conditions like with the QueryBuilder on $merge
but it does not work
$this->data['buildingsAndCircuits'] = $merged->orderBy('updated_at', 'DESC')->limit(3)->all();
thank you very much
Upvotes: 2
Views: 52
Reputation: 40663
Once you've called get
on each query then the query is executed and the result is returned. orderBy
will not longer work after that since what you have in $buildings, $circuits
and $merged
is a collection.
You can however do this:
$buildings = Building::published()->limit(3)->get();
$circuits = Circuit::published()->limit(3)->get();
$merged = $buildings->merge($circuits)->sortByDesc('updated_at');
$this->data['buildingsAndCircuits'] = $merged->all();
Check what else you can do on collections in the documentation
Upvotes: 2