douneiben2240 2016-11-16 04:04
浏览 44
已采纳

Laravel Eloquent - 查询构建器无法找到具有功能的列

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();
  • 写回答

2条回答 默认 最新

  • donglang6656 2016-11-16 05:07
    关注

    You forgot the aggregate function (in this case COUNT) in your HAVING condition:

    $query->where('genre_id', '55')
        ->orWhere('genre_id', '60')
        ->groupBy('game_id')
        ->havingRaw('COUNT(DISTINCT genre_id) = 2');
    

    Instead of adding several where() and orWhere() to your query, you could also use whereIn() which takes an array:

    $myArray = [55,60];
    $query->whereIn('genre_id', $myArray)
        ->groupBy('game_id')
        ->havingRaw('COUNT(DISTINCT genre_id) = 2');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部