I want to take last row of table using orderby. Results:
{"anime":[{"id":25,"title":"Black Clover","epnumber":14}, {"id":25,"title":"Black Clover","epnumber":13}, {"id":25,"title":"Black Clover","epnumber":12}, {"id":25,"title":"Black Clover","epnumber":11}, {"id":25,"title":"Black Clover","epnumber":10}, {"id":26,"title":"One Piece","epnumber":200}, {"id":26,"title":"One Piece","epnumber":199}]}
But I actually want is.
{"anime":[{"id":25,"title":"Black Clover","epnumber":14}{"id":26,"title":"One Piece","epnumber":200}]}
My code:
$anime = DB::table('seasons')->orderBy('episodes.epnumber', 'desc') ->join('animes','animes.id','seasons.animes_id') ->join('episodes','episodes.seasons_id','seasons.id') ->get(['animes.id', 'animes.title', 'episodes.epnumber'])->toArray();
Advertisement
Answer
You could just group the data and get the MAX episode number:
$anime = DB::table('seasons')->orderBy('episodes.epnumber', 'desc') ->join('animes','animes.id','seasons.animes_id') ->join('episodes','episodes.seasons_id','seasons.id') ->groupBy('animes.id', 'animes.title') ->get(['animes.id', 'animes.title', DB::raw('MAX(episodes.epnumber) as epnumber')])->toArray();