V
V
Volodymyr2021-04-03 12:17:40
Laravel
Volodymyr, 2021-04-03 12:17:40

How can I query Eloquent data from a database with only the latest data?

Hello!

How can I query Eloquent data from a database with only the latest data?
It is necessary to weed out from the request data that is duplicated but older by date.

For example, we have the following data:
id name marker num created_at
1 Test1 root 100 2021-03-18
2 Test2 user 100 2021-03-18
3 Test2 user 120 2021-03-21
4 Test3 guest 100 2021-03-22

And you need to get:
id name marker num created_at
1 Test1 root 100 2021-03-18
3 Test2 user 120 2021-03-21
4 Test3 guest 100 2021-03-22

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
JhaoDa, 2021-04-03
@volodyalesha86

Specifically, your request "preferably beautiful without DB" cannot be done.

\DB::query()
    ->from((new Name())->getTable(), 't')
    ->where('created_at', '=', function ($q) {
        $q
            ->from((new Name())->getTable(), 't2')
            ->selectRaw('MAX(t2.created_at)')
            ->whereRaw('t2.name = t.name')
            ->whereRaw('t2.marker = t.marker');
    })
    ->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question