doushan6161 2018-05-23 06:24
浏览 34
已采纳

Laravel雄辩地按最新的独特条目排序

I'm currently creating a basic inbox for a private messaging system which only displays the users which the logged in user has been in contact with if messages between the user and recipient exist. (Similar to how your standard instant messenger works)

The way I am getting this list is to check the messages table to see if any messages between the two users exist. If it does then list this in the inbox but since there will be many messages between the user, I am using a Laravel collection and the unique function to only display a recipient once. The user then can click on this recipient to see the message thread.

The issue I am having with is being able to sort this list by the latest message (e.g. sort by created_at)

How am I able to order this in order of the latest entry so that the most recent messages display at the top of the list in the inbox. Here is the code I using in my controller to get the list of recipients and attempt to sort by latest message:

    $messages = collect(Message::where('recipient_id', $user)->orderBy('created_at', 'desc')->get());

    $messagesUnique = $messages->sortBy('created_at')->unique('sender_id');

    $messagesUnique->values()->all();

Thanks

  • 写回答

1条回答 默认 最新

  • duanboniao5903 2018-05-23 07:31
    关注

    Define your relationships:

    class Message extends Model
    {
        public function sender()
        {
            return $this->belongsTo(User::class, 'sender_id');
        }
    
        public function recipient()
        {
            return $this->belongsTo(User::class, 'recipient_id');    
        }
    }
    

    In the User model:

    class User extends Authenticable
    {
        public function received()
        {
            return $this->hasMany(Message::class, 'recipient_id')->latest();
        }
    
        public function sent()
        {
            return $this->hasMany(Message::class, 'sender_id')->latest();
        }
    }
    

    Then for retrieving the messages:

    $user = Auth::user();
    $messages = $user->received->unique('sender_id');
    $sent = $user->sent->unique('recipient_id');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部