当我将一个表连接到另一个表时,我得到了这个错误。 我输入为关键字,但它不起作用,它给了我错误,例如找不到字段,我该如何解决此错误
法典:
Product::leftjoin('reviews','products.id','=','reviews.productID')
->select(array('products.*',
DB::raw('AVG(rating) as ratings_average')
))
->where(function($query) use ($categoriesID,$brands,$priceArray,$ratingArray)
{
$query->whereIn('categoryID',$categoriesID);
if(count($brands) > 0)
{
$query->whereIn('brandID',$brands);
}
$query->whereBetween('productSellingPrice',$priceArray);
if(count($ratingArray) > 0)
{
$query->whereBetween('ratings_average',$ratingArray);
}
})
->groupBy('products.id')
->get();
错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ratings_average' in 'where clause' (SQL: select `products`.*, AVG(rating) as ratings_average from `products` left join `reviews` on `products`.`id` = `reviews`.`productID` where (`categoryID` in (9, 11, 31) and `productSellingPrice` between 50 and 5000 and `ratings_average` between 1 and 2) group by `products`.`id`)
您可以找到$minRating
和maxRating
,而不是评级数组。通过这两个值,您可以像这样运行查询:
$query->whereBetween('rating',[$minRating,$maxRtaing]);
这个问题是一个SQL问题,它与范围有关。 我不精通 laravel 的 API,但生成的 SQL(基于您有用的错误消息)是:
select `products`.*, AVG(rating) as ratings_average
from `products` left join `reviews` on `products`.`id` = `reviews`.`productID`
where (`categoryID` in (9, 11, 31) and `productSellingPrice` between 50 and 5000
and `ratings_average` between 1 and 2) group by `products`.`id`)
问题是ratings_average
计算列属于GROUP BY
范围。 引用该列的唯一方法是在 HAVING
语句中。 您的 SQL 语句如下所示:
select `products`.*, AVG(`ratings`.`rating`) as ratings_average
where `products`.`id` = `reviews`.`productId`
group by `products`.`id`
having (`categoryID` in (9, 11, 31) and `productSellingPrice` between 50 and 5000
and `ratings_average` between 1 and 2)
从技术上讲,上面 having 语句中的前两个子句可能在您的 WHERE
子句中,但ratings_average
命名列只能在 HAVING
子句中引用。 WHERE 和 HAVING 都会限制您的结果,但 HAVING 是在分组发生后进行评估的。