Sort two Laravel objects in the correct order -
i have 2 eloquent objects want "merge" speak.
i dont know if merging best approach please come suggestions.
$customer = customer::find($customerid); $events = $customer->events()->unfinished()->orderby('created_at', 'asc')->get(); $notes = $customer->notes()->orderby('created_at', 'asc')->get();
events() hasmany = $customer->hasmany('events');
unfinished() scope = $query->where('status', '=', '0');
notes() hasmany = $customer->hasmany('notes');
i want merge $events
, $notes
can loop through these created_at falling correct order.
lets $notes contains 2 posts:
note 1 created_at: 2013-01-30 00:00:00 note 2 created_at: 2014-12-31 00:00:00
and $events contains 2 posts:
event 1 created_at: 2014-02-01 00:00:00 event 2 created_at: 2014-01-02 00:00:00
i want them falling this:
event 1 created_at: 2014-02-01 00:00:00 note 1 created_at: 2013-01-30 00:00:00 event 2 created_at: 2014-01-02 00:00:00 note 2 created_at: 2014-12-31 00:00:00
how best approach this?
union dident work unless 2 tables has same columns. did found answer: http://laravel.com/api/source-class-illuminate.support.collection.html#299-319
$customer = customer::find($customerid); $events = $customer->events()->unfinished()->get(); $notes = $customer->notes()->get(); $combined = $events->merge($notes);
edit: , sort combined collection:
$combined = $combined ->sortby(function($sort){ return $sort->created_at; })->reverse();
Comments
Post a Comment