我正在查看特定帖子的作者发布的所有评论.
foreach($post->user->comments as $comment)
{
echo "<li>" . $comment->title . " (" . $comment->post->id . ")</li>";
}
Run Code Online (Sandbox Code Playgroud)
这给了我
I love this post (3)
This is a comment (5)
This is the second Comment (3)
Run Code Online (Sandbox Code Playgroud)
我如何通过post_id订购,以便上面的列表被命令为3,3,5
TL; DR:需要每个发件人的最新消息.
在我的Laravel应用程序中,我有两个表:
用户:
消息:
当然还有模特.
用户模型:
public function messages() {
return $this->hasMany('App\Message', 'recipient_id');
}
Run Code Online (Sandbox Code Playgroud)
消息模型:
public function sender() {
return $this->belongsTo('App\User', 'sender_id');
}
public function recipient() {
return $this->belongsTo('App\User', 'recipient_id');
}
Run Code Online (Sandbox Code Playgroud)
当用户打开他的收件箱时,他应该看到来自任何其他用户的最新消息列表.
所以,如果有消息:
id sender_id recipient_id body created_at
1, 2, 1, hi, 2016-06-20 12:00:00
2, 2, 1, hi, 2016-06-21 12:00:00
3, 3, 1, hi, 2016-06-20 12:00:00
4, 3, 1, hi, 2016-06-21 12:00:00
Run Code Online (Sandbox Code Playgroud)
然后,id为1(recipient_id)的用户应该只看到ID为2和4的消息.
这是用户模型中的当前解决方案:
return Message::whereIn('id', function($query) {
$query->selectRaw('max(`id`)')
->from('messages')
->where('recipient_id', '=', …Run Code Online (Sandbox Code Playgroud)