douneiben2240 2016-11-16 12: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 13: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条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大