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.