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 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助