doushan6161 2018-05-23 14: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 15: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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错