I'm trying to generate this query using Laravel:
select mygames.id, mygames.name, mygames.slug, mygames.cover from mygames
left join mygame_mygenre on mygames.id = mygame_mygenre.mygame_id
left join mygame_myplatform on mygames.id = mygame_myplatform.mygame_id
where mygame_mygenre.mygenre_id in (8, 9, 31, 32, 33)
and mygame_myplatform.myplatform_id in (3, 6, 14, 34, 37, 39, 46, 48, 72, 130)
and mygames.id <> 1990
and mygames.summary is not null
and (select count(mygame_id) from mygame_myplatform where mygame_id = mygames.id) > 1
group by mygames.id, mygames.name, mygames.slug, cover
order by RAND()
limit 6
My current code is:
$games = DB::table('mygames')
->leftjoin('mygame_mygenre', 'mygames.id', '=', 'mygame_mygenre.mygame_id')
->leftjoin('mygame_myplatform', 'mygames.id', '=', 'mygame_myplatform.mygame_id')
->select('mygames.id', 'mygames.name', 'mygames.slug', 'cover')
->when($genres_id, function ($query, $genres_id) {
return $query->whereIn('mygame_mygenre.mygenre_id', $genres_id);
})
->when($platforms_id, function ($query, $platforms_id) {
return $query->whereIn('mygame_myplatform.myplatform_id', $platforms_id);
})
->where('mygames.id', '<>', $this->id)
->whereNotNull('mygames.summary')
->where(function ($query) {
$query->selectRaw('count(mygame_id)')
->from('mygame_myplatform')
->where('mygame_id', 'mygames.id');
}, '>', 1)
->groupBy('mygames.id', 'mygames.name', 'mygames.slug', 'cover')
->inRandomOrder()
->take(6)
->get();
This code is not working because inside the closure function I was unable to pass the name of the mygames table with the id field. Laravel is interpreting as a text parameter and not as a table.field
->where(function ($query) {
$query->selectRaw('count(mygame_id)')
->from('mygame_myplatform')
->where('mygame_id', 'mygames.id'); <<<<<<<<<<<<<
}, '>', 1)
I tried to use 'use ()' but it didn't work either.
Could you help me?