Reputation: 3115
I have merged two Eloquent collections to produce the following output:
[
"2015-03-05 21:54:19" => 100
"2015-07-05 18:54:00" => 4
"2015-06-30 21:53:29" => 3
]
Where the first column is updated_at timestamp and the last column is the IDs for two tables.
My code is as follows:
$jobs = $this->user->find($userId)->jobs()->lists('id', 'updated_at');
$bids = $this->user->find($userId)->bids()->lists('id', 'updated_at');
$all = $jobs->merge($bids)->sortByDesc('updated_at');
dd($all);
My question is, how can I sort the arrays so that they're ordered in descending order by the updated_at column?
Upvotes: 4
Views: 3437
Reputation: 505
For descending order use sortByDesc
$all = $jobs->merge($bids)->sortByDesc('updated_at');
For ascending order use sortBy
$all = $jobs->merge($bids)->sortBy('updated_at');
Upvotes: 6
Reputation: 964
Collections has a method called flip(), which as it sounds flips the key with the value. You could in this case simply flip after the merge and sort by value then flip again to get the original collection.
$all = $jobs->merge($bids)->flip()->sortByDesc('')->flip();
If you only care about the keys I would really recommend just reversing the get statements sorting the values and pulling the keys in the sorted order.
$jobs = $this->user->find($userId)->jobs()->lists('updated_at', 'id');
$bids = $this->user->find($userId)->bids()->lists('updated_at', 'id');
$all = $jobs->merge($bids)->sortByDesc('')->keys();
I also don't know how you have your Model setup but you may possibly be able to pull the jobs and bids in one query with the with() in eloquent.
$data = $this->user->find($userId)->with('jobs','bids').. //etc
Upvotes: 1