我有2个Eloquent对象,我想“合并”可以这么说。
我不知道合并是否是最佳方法,请提出建议。
$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');
未完成()是范围= $ query->其中('status','=','0');
Notes()是一个hasMany = $ customer-> hasMany('notes');
我想将$events
和$notes
合并在一起,以便我可以使用created_at以正确的顺序循环这些。
让我们说$ notes包含2个帖子:
note 1
created_at: 2013-01-30 00:00:00
note 2
created_at: 2014-12-31 00:00:00
$ events包含2个帖子:
event 1
created_at: 2014-02-01 00:00:00
event 2
created_at: 2014-01-02 00:00:00
我希望他们这样下降:
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
我最好如何处理这个问题?
答案 0 :(得分:0)
Union dident工作。 但我确实找到了这个答案: 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);
编辑: 并对合并的集合进行排序:
$combined = $combined ->sortBy(function($sort){
return $sort->created_at;
})->reverse();