我有3个模型
- User(用户)
- Channel(频道)
- Reply(回复)
模型关系
user
拥有belongsToMany('App\Channel');
channel
拥有hasMany('App\Reply', 'channel_id', 'id')->oldest();
假设我有2个频道
- channel-1
- channel-2
channel-2
拥有比 channel-1
更晚的回复
现在,我想按照用户所在频道的当前回复来排序用户的频道,就像一些聊天应用程序一样。我该如何像这样排序用户的频道?
- channel-2
- channel-1
我已经尝试了一些代码,但没有任何效果。
// User Model
public function channels()
{
return $this->belongsToMany('App\Channel', 'channel_user')
->withPivot('is_approved')
->with(['replies'])
->orderBy('replies.created_at'); // error
}
// also
public function channels()
{
return $this->belongsToMany('App\Channel', 'channel_user')
->withPivot('is_approved')
->with(['replies' => function($qry) {
$qry->latest();
}]);
}
// but i did not get the expected result
编辑 另外,我尝试了这个。是的,我得到了预期的结果,但如果没有回复,它将无法加载所有频道。
public function channels()
{
return $this->belongsToMany('App\Channel')
->withPivot('is_approved')
->join('replies', 'replies.channel_id', '=', 'channels.id')
->groupBy('replies.channel_id')
->orderBy('replies.created_at', 'ASC');
}