2015-12-21 151 views
0

我有一個屬於許多'事件'的用戶模型,也屬於許多'me_resource'。雄辯。獲取多個關係並對它們進行排序

對於活動日誌,我想獲取所有用戶事件和我的資源,然後通過pivot_new_at屬性對它們進行排序。

像這樣的東西是什麼,我找

user->events()->me_resources()->orderBy('pivot.updated_at')->get() 

但當然me_resource不在事件上用戶的關係,也它們分別通過不同的數據透視表與用戶。

這裏的查詢應該返回什麼

id:87, resource_name:'hello', ..., updated_at:21/12/2015 //newest 
id:32, event_name:'meeting', ..., updated_at: 20/11/2015 // second newest 
id:11, resource_name:'questions', ..., updated_at: 27/02/2015 // third newest 

回答

1

如果你想用雄辯的關係,我建議使用Collection s到處理邏輯使你能保持一個例子。使用查詢生成器可能會更有效。

$user = User::with('events', 'me_resources')->find($user_id); 

$collection = new \Illuminate\Database\Eloquent\Collection(); 
$collection->merge($user->events); 
$collection->merge($user->me_resources); 
$results = $collection->sortByDesc('updated_at');