当我加入另一个表时,我在查询中发现了错误

时间:2016-01-27 10:57:52

标签: php mysql sql laravel model-view-controller

当我将一张桌子加入另一张桌子时,我收到了这个错误。我把它作为关键字,但它不工作它给我错误像字段没有找到我怎么能解决这个错误

代码:

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`)

2 个答案:

答案 0 :(得分:0)

您可以找到$minRatingmaxRating,而不是对数组进行评分。通过这两个值,您可以像这样运行查询:

$query->whereBetween('rating',[$minRating,$maxRtaing]);

答案 1 :(得分:0)

问题是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进行评估。