复杂的雄辩SQL

时间:2017-10-09 15:26:25

标签: mysql laravel eloquent

我试图在Laravel 5.5中运行以下查询:

select `colours`.`id` AS `id`
     ,`colours`.`description` AS `description`
     ,`vehicle_colour_and_trims`.`colour_id` AS `colour_id`
     ,`colours`.`code` AS `code`
     ,`vehicle_options`.`basic_price` AS `basic_price`
     ,`vehicle_options`.`mrp` AS `mrp`
     ,`vehicle_options`.`vat` AS `vat` 
from ((`vehicle_colour_and_trims` 
join `colours` 
  on ((`vehicle_colour_and_trims`.`colour_id` = `colours`.`id`))) 
join `vehicle_options` 
  on ((`colours`.`option_id` = `vehicle_options`.`option_id`)))  
WHERE vehicle_colour_and_trims.vehicle_id = 116922 
group by `colours`.`code` 
order by `colours`.`description`

这是否超出了Eloquent?

1 个答案:

答案 0 :(得分:0)

如果要执行复杂查询,laravel提供了查询构建器工具,您可以使用数据库外观上的表方法开始查询。

在您的控制器中,您必须添加以下行才能使用数据库外观:

use Illuminate\Support\Facades\DB;

您要执行的查询将构造如下:

    $query = DB::table('vehicle_colour_and_trims')
             ->join('colours', 'vehicle_colour_and_trims.colour_id', '=','colours.id')
             ->join('vehicle_options', 'colours.option_id', '=','vehicle_options.option_id')      
             ->select('colours.id AS id',
                      'colours.description AS description',
                      'vehicle_colour_and_trims.colour_id AS colour_id', 
                      'colours.code AS code',
                      'vehicle_options.basic_price AS basic_price',
                      'vehicle_options.mrp AS mrp',
                      'vehicle_options.vat AS vat')
             ->where('vehicle_colour_and_trims.vehicle_id','=', 116922)
             ->groupBy('colours.code')
             ->orderBy('colours.description', 'desc')
             ->get();

您可以在laravel文档中了解有关查询构建器的更多信息

https://laravel.com/docs/5.5/queries

使用此查询时出现SQLSTATE [42000]错误,因为在mysql中默认启用了sql_mode = ONLY_FULL_GROUP_BY **,这意味着MySQL拒绝选择列表,HAVING条件或ORDER BY引用非聚合的查询未在GROUP BY子句中命名或在功能上依赖于它们的列。

为了将列添加到选择列表而不必将它们添加到GROUP_BY子句中,您必须为不必存在的每个列使用函数 ANY_VALUE()在条款中,试试这个:

$query = DB::table('vehicle_colour_and_trims')
         ->join('colours', 'vehicle_colour_and_trims.colour_id', '=','colours.id')
         ->join('vehicle_options', 'colours.option_id', '=','vehicle_options.option_id')      
         ->select(DB::raw('ANY_VALUE(colours.id) AS id,
                           ANY_VALUE(colours.description) AS description,
                           ANY_VALUE(vehicle_colour_and_trims.colour_id) AS colour_id,
                           colours.code AS code,
                           ANY_VALUE(vehicle_options.basic_price) AS basic_price,
                           ANY_VALUE(vehicle_options.mrp) AS mrp,
                           ANY_VALUE(vehicle_options.vat) AS vat'))
         ->where('vehicle_colour_and_trims.vehicle_id','=', 116922)
         ->groupBy('colours.code')
         ->orderBy('colours.description', 'desc')
         ->get(); 

DB :: raw()函数允许您创建原始表达式

更多信息:

https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html