Laravel-GroupAy as Alias

时间:2018-08-29 05:13:50

标签: laravel laravel-5 eloquent laravel-orm

我的一项功能中具有以下功能,但希望将其称为名为Date的别名:

$loads = $query->get()->groupBy(function($item){
    return Carbon::parse($item->dateTime)->format('F j, Y');
});

$query的开头为:$query = DB::table('loads')...

,字段dateTime是时间戳记。

是否有适当的方法来包括别名?谢谢!

//使用整个控制器功能更新:

public function apiList(Request $request){
    $query = DB::table('loads')
              ->leftJoin('shipments', 'loads.shipmentID', '=', 'shipments.id')
              ->leftJoin('equipment as tractor', 'loads.tractorID', '=', 'tractor.id')
              ->leftJoin('employees', 'loads.driverID', '=', 'employees.id')
              ->leftJoin('customers as shipperCustomer', 'shipments.ship_from', '=', 'shipperCustomer.id')
              ->leftJoin('customers as consigneeCustomer', 'shipments.ship_to', '=', 'consigneeCustomer.id')
              ->select('loads.id','shipments.pro_number','shipments.id','employees.last_name as driver','tractor.unit_id as tractor','loads.dateTime','shipperCustomer.customer_name as ShipperCustomerName','consigneeCustomer.customer_name as ConsigneeCustomerName','shipments.cn_shipfromName as ShipperName','shipments.cn_shiptoName as ConsigneeName');

    if($request->type){
        $query->where('loads.type', $request->type);
    }

    if($request->status){
        $query->where('loads.status', $request->status);
    }

    if($request->type == 1 && $request->status == 2){
        $query->whereIn('shipmentID', function ( $query ) {
            $query->select('shipmentID')->from('loads')->groupBy('shipmentID')->havingRaw('count(*) = 1');
        });
    }

    $loads = $query->get()->groupBy(function($item)
                {
                  return Carbon::parse($item->dateTime)->format('F j, Y');
                });

    return response()->json([
                ['loads'=>$loads],
                ['time'=>Carbon::now()]
            ]);

//更新以显示当前返回的数据:

enter image description here


///

不幸的是,我得到以下信息:

  

“ SQLSTATE [42000]:语法错误或访问冲突:1055 SELECT列表的表达式#1不在GROUP BY子句中,并且包含非聚合列'truckin.loads.id',该列在功能上不依赖于GROUP BY子句中的列;这与sql_mode = only_full_group_by(SQL:选择loadsidshipmentspro_numbershipmentsid,{{ 1}}。employeeslast_namedrivertractorunit_idtractorloads如{{1} },dateTimeloadsDTshipperCustomercustomer_nameShipperCustomerNameconsigneeCustomercustomer_nameConsigneeCustomerName为{ shipmentscn_shipfromNameShipperName来自shipments的{​​{1}}在cn_shiptoName上加入ConsigneeNameloads = { {1}}。shipmentsloads上以shipmentID左加入shipmentsid = equipmenttractor左加入{ loads上的{1}}。tractorID = tractoridemployees上以loads的身份加入driverID。{{ 1}} = employeesidcustomers上以shipperCustomer的身份加入shipmentsship_from = shipperCustomer。{{1 }},其中idcustomers = 1和consigneeCustomershipments = 2和ship_to(从consigneeCustomer中选择idloads分组,计数(*)= 1)按DATE_FORMAT分组(loads.dateTime,“%M%e,%Y”))“

//用另一个返回更新 enter image description here

//一些更新-2018年8月30日

根据您的最初建议,我进行了更新,但收到此错误:

  

“ SQLSTATE [42000]:语法错误或访问冲突:1055 SELECT列表的表达式#2不在GROUP BY子句中,并且包含未聚合的列'truckin.shipments.pro_number',该列在功能上不依赖于GROUP BY子句中的列;这与sql_mode = only_full_group_by不兼容(SQL:选择ANY_VALUE(loads.id),ships.pro_number,ships.id,employees.last_name作为驱动程序,trainer.unit_id作为拖曳程序,loads.dateTime,shipperCustomer.customer_name作为ShipperCustomerName,consigneeCustomer {customer.name.shiper_name作为发货人姓名,shipments.cn_shiptoName作为发货人姓名,shipments.cn_shiptoName作为发货人姓名,来自type的{​​{1}}在loads上左加入statusshipmentID = shipmentID。{{ 1}}在loads上以shipmentID的身分加入loadsshipments = loadsshipmentID在{{ 1}}。shipments = idequipmenttractor上以loads左加入tractorIDtractor = {{1 }}。idemployees上以loads的身份加入driverIDemployees = idcustomers,其中{{1} }。shipperCustomer = 2和shipmentsship_from = 1个DATE_FORMAT组(loads.dateTime,“%M%e,%Y”))“

所以我继续前进,由于级联失败,最终不得不执行以下操作:

  

$ loads = $ query-> groupBy(DB :: raw('DATE_FORMAT(loads.dateTime,“%M%e,%Y”)'),'loads.dateTime','shipments.id',' shippings.pro_number','driver','tractor','ShipperCustomerName','ConsigneeCustomerName','ShipperName','ConsigneeName')-> get();

现在显然这是不对的,但这是我可以获得任何形式的回报的唯一方法,结果是:

enter image description here

2 个答案:

答案 0 :(得分:0)

最后一种方法,对此进行更改:

select('loads.id','shipments.pro_number','shipments.id','employees.last_name as driver','tractor.unit_id as tractor','loads.dateTime','shipperCustomer.customer_name as ShipperCustomerName','consigneeCustomer.customer_name as ConsigneeCustomerName','shipments.cn_shipfromName as ShipperName','shipments.cn_shiptoName as ConsigneeName');

对此:

selectRaw('ANY_VALUE(loads.id), shipments.pro_number, shipments.id, employees.last_name as driver, tractor.unit_id as tractor, loads.dateTime, shipperCustomer.customer_name as ShipperCustomerName,consigneeCustomer.customer_name as ConsigneeCustomerName,shipments.cn_shipfromName as ShipperName,shipments.cn_shiptoName as ConsigneeName');

并将groupBy保留为

$query->groupBy(DB::raw('DATE_FORMAT(loads.dateTime, "%M %e, %Y")'))->get();

如果您想进一步了解此解决方案,请检查:https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_any-value

检查链接上的示例,并注意此处引用的内容:

  

发生失败是因为address是未聚合的列,既未在GROUP BY列中命名,也未在功能上依赖于它们。结果,每个名称组内行的地址值是不确定的。有多种方法可以使MySQL接受查询:

     

更改表以使名称成为主键或唯一的NOT NULL列。这使MySQL能够确定该地址在功能上取决于名称。即,地址由名称唯一地确定。 (如果必须允许使用NULL作为有效名称值,则此技术不适用。)

     

使用ANY_VALUE()引用地址:

     

从t GROUP BY名称中选择名称,ANY_VALUE(地址)和MAX(年龄);

     

在这种情况下,MySQL会忽略每个名称组中地址值的不确定性,并接受查询。如果您根本不在乎为每个组选择未聚合列的哪个值,这可能会很有用。与SUM()或COUNT()之类的函数不同,ANY_VALUE()不是聚合函数。它只是起到抑制不确定性测试的作用。

     

禁用ONLY_FULL_GROUP_BY。如上一项所述,这等效于在启用ONLY_FULL_GROUP_BY的情况下使用ANY_VALUE()。

答案 1 :(得分:0)

config / database.php 的数据库配置中,更改strict => false 默认为 true