【问题标题】:How to get users by last message in Laravel Eloquent如何通过 Laravel Eloquent 中的最后一条消息获取用户
【发布时间】:2022-01-29 04:24:13
【问题描述】:

我目前正在使用 Laravel 8 和 VueJS 开发一个简单的聊天应用程序。我需要按用户的最新消息对用户进行排序,并与用户一起获取最后一条消息。如果有人对此操作有想法,下面是我正在使用的表格。如果是 Eloquent 方法就更好了。

用户表

create table users
(
    id                        bigint unsigned auto_increment
    primary key,
    name                      varchar(255)                  not null,
    email                     varchar(255)                  not null,
    email_verified_at         timestamp                     null,
    password                  varchar(255)                  not null,
    two_factor_secret         text                          null,
    two_factor_recovery_codes text                          null,
    remember_token            varchar(100)                  null,
    status                    varchar(255) default 'online' not null,
    last_seen                 timestamp                     null,
    current_team_id           bigint unsigned               null,
    profile_photo_path        varchar(2048)                 null,
    created_at                timestamp                     null,
    updated_at                timestamp                     null,
    constraint users_email_unique
    unique (email)
)
collate = utf8mb4_unicode_ci;

私人消息表

create table private_messages
(
    id          bigint unsigned auto_increment
    primary key,
    sender_id   bigint unsigned not null,
    receiver_id bigint unsigned not null,
    message     varchar(1000)   not null,
    delete_type varchar(15)     null,
    created_at  timestamp       null,
    updated_at  timestamp       null,
    deleted_at  timestamp       null,
    constraint private_messages_receiver_id_foreign
    foreign key (receiver_id) references users (id)
    on delete cascade,
    constraint private_messages_sender_id_foreign
    foreign key (sender_id) references users (id)
    on delete cascade
)
collate = utf8mb4_unicode_ci;

【问题讨论】:

  • 发件人和/或收到的最后一条消息?你想基于哪个{create|update|deleted}_at 字段?哪个 MySQL 服务器版本?
  • 我想通过eiter sender_id 或receiver_id 获取最后一条消息等于经过身份验证的用户。它可以基于 created_at 文件

标签: mysql laravel eloquent


【解决方案1】:

在用户模型中创建关系函数

public function privateMessages()
{
    return $this->hasMany(PrivateMessage::class)->orderBy('id','DESC');
}

然后使用

$users = User::with('privateMessages')->all();

在此结果中,消息按 id desc 排序。

【讨论】:

  • 这对我不起作用。假设 John 登录了他的帐户并获得了用户列表。在该列表中,每个用户项都有最后一条消息。最后一条消息表示 John 从其他用户发送或接收。
猜你喜欢
  • 2021-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-26
  • 2019-03-31
相关资源
最近更新 更多