[英]Laravel(5.6) eloquent order by last message
I have a User
model which has a reference to MessageParticipant
model (returns all the message subjects the user participating in) 我有一个
User
模型,其中引用了MessageParticipant
模型(返回用户参与的所有消息主题)
public function messages()
{
return $this->hasMany(MessageParticipant::class);
}
The MessageParticipant
refers to a MessageSubject
model (returns the message subject participants belong to) MessageParticipant
引用MessageSubject
模型(返回参与者所属的消息主题)
public function message_subject()
{
return $this->belongsTo(MessageSubject::class);
}
The MessageSubject
model refers to a Message
model (return all the messages within message subject) MessageSubject
模型引用一个Message
模型(返回消息主题内的所有消息)
public function messages()
{
return $this->hasMany(Message::class);
}
I want to return all the message subjects a user is participating in, ordering according to latest message entry to the message subject. 我想返回用户参加的所有邮件主题,并根据最新的邮件条目对邮件主题进行排序。 Below is what I've tried so far.
以下是到目前为止我尝试过的。
$messages = $user->messages()->search($search)
->join('messages', 'messages.message_subject_id', '=', 'message_subject.id')
->select('message_subject.*', 'messages.created_at AS latest_message_at')
->orderByDesc('latest_message_at')
->paginate(30);
How can I do it? 我该怎么做?
You can use a BelongsToMany
relationship to get the message subjects directly: 您可以使用
BelongsToMany
关系直接获取消息主题:
class User extends Model {
public function messageSubjects() {
return $this->belongsToMany(MessageSubject::class, 'message_participants');
}
}
Then use it with a modified withCount()
to get the latest message: 然后将其与修改后的
withCount()
以获取最新消息:
$messages = $user->messageSubjects()
->withCount(['messages as latest_message' => function($query) {
$query->select(DB::raw('max(messages.created_at)'));
}])
->search($search)
->orderByDesc('latest_message')
->paginate(30);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.