gpt4 book ai didi

php - Laravel 通过多列分组获取最新记录

转载 作者:行者123 更新时间:2023-11-29 02:38:52 25 4
gpt4 key购买 nike

你好,我是 Laravel 的新手,我被 Laravel Eloquent 复杂查询困住了

这是我的消息表结构

---|-----------|-------------|--------
ID | sender_id | receiver_id | message
---|-----------|-------------|--------
1 | 1 | 2 | Hello
2 | 1 | 2 | Hey hello reply
3 | 2 | 1 | Good
4 | 3 | 2 | Hey GOOD Morning
5 | 3 | 2 | good night

我想从消息表中检索最近的聊天,无论用户是发件人还是接收者我想使用多列和最新的只有一条消息的 groupBy 检索

为用户 2(发送者或接收者)点赞

-----------|-------------|---------------
sender_id | receiver_id | message
-----------|-------------|---------------
2 | 1 | Good
3 | 2 | good night

这是我 Eloquent 问题

$user = auth()->user(); //User_id 2 based on logged in user either sender or reciever
Message::where('user_id', $user->id)
->orWhere('receiver_id', $user->id)
->select('user_id','receiver_id')
->groupBy('user_id','receiver_id')
->get();

结果

all: [
App\Models\Message {
user_id: 1,
receiver_id: 2,
}, // don't want this record
App\Models\Message {
user_id: 2,
receiver_id: 1,
},
App\Models\Message {
user_id: 3,
receiver_id: 2,
},
],

如果我尝试使用 latest() 方法,那么它会显示表中存在错误时间戳

Illuminate/Database/QueryException with message 'SQLSTATE[42000]:

Syntax error or access violation: 1055 Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column

我不想更新 config/database.php 中的 mysql_strict 模式

它不能正常工作,任何人都可以帮助我或任何好的建议或想法

任何帮助将不胜感激

最佳答案

你能想出如何在 Laravel 中表达它吗?

**Schema (MySQL v5.7)**

CREATE TABLE my_table
(ID SERIAL PRIMARY KEY
,sender_id INT NOT NULL
,receiver_id INT NOT NULL
,message VARCHAR(50) NOT NULL
);

INSERT INTO my_table VALUES
(1,1,2,'Hello'),
(2,1,2,'Hey hello reply'),
(3,2,1,'Good'),
(4,3,2,'Hey GOOD Morning'),
(5,3,2,'good night');

---

**Query #1**

SELECT a.*
FROM my_table a
JOIN
( SELECT MAX(id) id
FROM my_table
WHERE 2 IN(sender_id,receiver_id)
GROUP
BY LEAST(sender_id,receiver_id)
, GREATEST(sender_id,receiver_id)
) b
ON b.id = a.id;

| ID | sender_id | receiver_id | message |
| --- | --------- | ----------- | ---------- |
| 3 | 2 | 1 | Good |
| 5 | 3 | 2 | good night |

---

View on DB Fiddle

关于php - Laravel 通过多列分组获取最新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57313592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com