mercredi 16 novembre 2016

Laravel Eloquent - Query builder cant find column with having function

I have a pivot table 'game_genre'(with game_id and genre_id). The game and genre model has a belongsToMany relationship similar to example below.

I have been attempting to gather the games which contain both genre_id of 60 and 55 together. I have been getting the correct result using the following SQL query, but when using the following query builder I end up getting a column not found error when using the having() function.

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'genre_id' in 'having clause'

Im not sure how else to structure the query builder?

MODEL:

class Game extends Model
{    
    public function genres()
    {
         return $this->belongsToMany('App\Genre');
    }
}

SQL:

SELECT *
FROM game_genre
WHERE genre_id = 55 OR genre_id = 60
GROUP BY game_id
HAVING COUNT(DISTINCT genre_id) = 2;

CONTROLLER:

    $game = Game::whereHas('genres', function ($query)
    {
        $query->where('genre_id', '55')
            ->orWhere('genre_id', '60')
            ->groupBy('game_id')
            ->having('genre_id','=', 2);
    })->get();



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire