我有3种型号laravel雄辩排序关系
- 用户
- 通道
- 回复
模型关系
user
有belongsToMany('App\Channel');
channel
有hasMany('App\Reply', 'channel_id', 'id')->oldest();
比方说,我有2个通道 - 通道1 - 通道2
channel-2
比channel-1
最新回复,现在,我想订购用户的通道通过其频道的当前答复。 就像一些聊天应用程序。 我该如何订购用户的频道?
- 通道2
- 信道-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');
}
编辑:
这种情况下,更愿意“加盟”而不是“与” –
嗯,所以我不能用雄辩.. – Hitori
@kap做到这一点? il.dev嗨,我试过连接方法。并按我的预期工作。但它只会返回所有有回复的频道。 – Hitori