0
votes

Comment obtenir les dernières lignes pour chaque identifiant d'utilisateur à Laravel?

id  user_id  name    qty     datetime
--- ---------  ----    ----    -----------
5   1           c      2       2019-12-21 12:26:06
4   2           a      2       2019-12-25 12:26:04

2 commentaires

Alors les dernières lignes pour chaque identifiant d'utilisateur?


oui @ Vivek_23 c'est juste


3 Réponses :


1
votes

Dans Pure SQL, vous pouvez filtrer avec une sous-requête corrélée:

select t.*
from mytable t
where t.datetime = (
    select max(t1.datetime) from mytable t1 where t1.user_id = t.user_id
)


0 commentaires

1
votes

ou une sous-requête non corrélée ...

select x.*
from mytable x
join (
    select user_id, max(t1.datetime) datetime from mytable group by user_id
) y
on y.user_id = x.user_id
and y.datetime = x.datetime


0 commentaires

0
votes

modèles: strong>

utilisateurs: em> id, nom, email, etc ...

Commandes: em> user_id, qty, nom, datetétime, etc. p>

Query modèle: strong> p>

DB::table('orders')->orderBy('datetime', 'desc')->get()->unique('user_id');


0 commentaires