我有这个查询
$query= Book_detail::groupBy('ddate', 'book_details.room_id')
->join('books', 'book_id', '=', 'books.id')
->join('rooms', 'book_details.room_id', '=', 'rooms.id')
->selectRaw('sum(books.room_qty) as sum, ddate, book_details.room_id,
rooms.room_qty - sum(books.room_qty) as stock')
->whereRaw('stock >= 5');
但出现错误
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'stock' in 'where clause'
我认为是因为“股票”列是附加列。所以我尝试像这样改变
->whereRaw('stock >= 5');
到
->whereRaw('rooms.room_qty - sum(books.room_qty) >= 5');
但这没用,因为whereRaw无法接受总和。另一种方法是使用havingRaw,
->whereRaw('rooms.room_qty - sum(books.room_qty) >= 5');
但是使用havingRaw我得到了错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'rooms.room_qty' in 'having clause'
在其他情况下,我认为我可以使用子查询。但老实说,我不知道该怎么做。