我有两个与数据透视表多对多关系相关的表,conversations_user。我的控制器工作正常:
控制者
public function create()
{
$loginuser = User::find(Auth::user()->id);
$user_id = $loginuser->id;
$conversations = $loginuser->conversations;
return View::make('brightcms.Conversations.Conversations',array('user_id'=>$user_id,'conversations'=>$conversations));
}
现在,我想根据对话表+ reverse()中的
created_at
列以降序排列对话。我试过了 :$conversations = $loginuser->conversations->orderBy('created_at','desc')->get()->reverse();
但它返回一条错误消息。谢谢!
最佳答案
如果您愿意,可以按期望的顺序懒惰地急于加载对话
public function create()
{
$loginuser = Auth::user();
$loginuser->load(['conversations' => function($q)
{
$q->orderBy('created_at', 'desc');
}]);
View::make('....', ['user' => $loginuser]);
}
$user->conversations; // your ordered conversations collection
如果您已经有了该集合,则可以
sortBy
或sortByDesc
。尽管如前所述,您可以按顺序访问集合中的reverse
,但您只是希望将其取反。Eager Loading w/ Constraints
Collection Methods