I
I
im_dimas2019-01-11 23:27:37
Laravel
im_dimas, 2019-01-11 23:27:37

How to build a database query in laravel?

Today I started to master laravel, I can not collect the request to display the necessary data.
Here is the request:

$res = DB::table('lastmes')
      ->groupBy('peer_id')
      ->orderBy('id','desc')
      ->limit('10')
      ->get();

It doesn't work quite right. How would it be more correct to say ..
Let's say if the table contains the following rows:
id|peer_id
1|5
2|5
3|4
4|4
5|4
6|4
Then the query that I described above will return the following rows:
3|4
1|5
And I need the following rows:
6|4
2|5
In short, I need to display unique rows from the table, and when "unique", select a row with a large id value
How to build such a query?
UPD: for clarity, I'll tell you what I'm trying to do.
I have a chat bot in VK community
As you know, if you go to "community messages", only dialogs will be shown in it, not conversations, I want to write a simple application in which both conversations and bot dialogs will be shown, naturally, all messages that come to the bot are recorded in the database, tables have the following structure:
id - record id
data - json object with data that came from the callback api
peer_id - from the dialog
Records with peer_id, of course, repeat, so I want to display unique ones, like messages in VK

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
holfza, 2019-01-11
@dimas199862

Probably something like this

$res = DB::table('lastmes')
      ->select(DB::raw('MAX(id) as id, peer_id'))
      ->groupBy('peer_id')
      ->orderBy('id','desc')
      ->limit('10')
      ->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question