Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bysior's avatar

Problem with Eloquent, join, group by and max()

Hi everyone, I'm still learning laravel and eloquent and I have a little problem with eloquent...

I have a three tables:

Schema::create('fishes', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->bigInteger('type_id')->unsigned();
            $table->foreign('type_id')->references('id')->on('fish_types')->onDelete('cascade');
            $table->float('length');
});

 Schema::create('fish_types', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->unique();
            $table->string('name_raw')->unique();
        });

 Schema::create('photos', function (Blueprint $table) {

            $table->bigIncrements('id');
            $table->string('photoable_type');
            $table->string('photoable_id');
            $table->string('path');

        });

I have model Fish and relations with fish types and photos. And its work, everything is fine, for example:

$f = Fish::with('photos', 'fishery', 'type')
        ->when($filters['userId'], function ($query) use ($filters) {
            return $query->where('user_id', $filters['userId']);
        });

But i want get from db the longest fish of each types who belongs to user, of course with photos. I have mysql question:

$sql = "SELECT id
        FROM fishes f1
        JOIN (
          SELECT type_id, MAX(`length`) AS pb
          FROM fishes
          where user_id = 6
          GROUP BY type_id) AS f2
        ON f1.type_id = f2.type_id and f2.pb = f1.length where f1.user_id = 6";

so i have id of the fishes. But what next? Same query "whereIn(Coulumn_name, Array)" ?

	$sth = DB::getPdo()->prepare($sql);
        $sth->execute();
        $quy = $sth->fetchAll(\PDO::FETCH_COLUMN, 0);

        $f = Fish::with('photos', 'fishery', 'type')
        ->where('user_id', 6)
        ->whereIn('id', $quy)->get();

Or I do it wrong? Can You help me? :)

T.

0 likes
1 reply
jlrdw's avatar

I's suggest a visual query designer. I use access via odbc, but a decent free one is sqLeo.

Also an example of a basic eloquent groupby:

$quy = Powner::query()->leftJoin('dc_pets', 'dc_powners.ownerid', '=', 'dc_pets.ownerid')
                ->select('dc_powners.ownerid', 'dc_powners.oname')
                ->selectRaw('count(dc_pets.petid) as countOfPets')
                ->groupby('dc_powners.ownerid')
                ->orderby('dc_powners.oname')
                ->get();

Results basically give:

ownerid, oname, countOfPets

Like:

5|Bob|3
4|Greg|9
2|Rob|1

These types of queries can take a little trial and error.

Please or to participate in this conversation.