2014-02-06 42 views
0

我有2個雄辯的對象,我想「合併」可以這麼說。按正確的順序排列兩個Laravel對象

我不知道如果合併是最好的方法,請帶上建議。

$customer = Customer::find($customerId); 

$events = $customer->Events()->Unfinished()->orderBy('created_at', 'asc')->get(); 

$notes = $customer->Notes()->orderBy('created_at', 'asc')->get(); 

活動()是一個的hasMany = $客戶 - >的hasMany( '事件');未完成()是一個範圍= $查詢 - >其中('狀態','=','0'); ()是一個hasMany = $ customer-> hasMany('notes');

我想合併$events$notes在一起,這樣我可以循環這些與created_at下降正確的順序。

比方說$票據包含2個職位:

note 1 
    created_at: 2013-01-30 00:00:00 
note 2 
    created_at: 2014-12-31 00:00:00 

和$事件中包含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

我有這樣的事情在那裏我的created_at想爲了結果從2個表。我嘗試使用聯合來組合它們。請參閱http://stackoverflow.com/questions/21497865/sorting-union-queries-with-laravel-4-1 – JackPoint

回答

0

聯合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();