jurde
jurde

Reputation: 57

Laravel get latest records with group by with multiple column

Hello I'm new in Laravel I'm stuck in a complex query with Laravel eloquent

Here is my messages table structure

---|-----------|-------------|--------
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

I want to retrieve recent chat from messages table either user is sender or receiver I want to retrieve with a groupBy using multiple columns and with latest only one message

Like for User 2 (Either sender or receiver)

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

Here is my eloquent query

$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();

Result

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,
   },
],

If I try to use latest() method then it's showing error timestamp is there in a table

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

I don't want to update mysql_strict mode in config/database.php

it's not working properly can anyone help me or any good suggestion or idea

Any help will appreciate

Upvotes: 1

Views: 2833

Answers (1)

Strawberry
Strawberry

Reputation: 33945

Can you figure out how to express this in 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

Upvotes: 1

Related Questions