Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何选择有说服力的聚合_Php_Mysql_Database_Laravel - Fatal编程技术网

Php 如何选择有说服力的聚合

Php 如何选择有说服力的聚合,php,mysql,database,laravel,Php,Mysql,Database,Laravel,我有两种型号:用户和交易,带有用户id,类型,以及金额字段。我希望能够选择具有按类型分组的事务数组的用户,如下所示: { // User instance 'id': 123, 'username': 'John' 'transactions': [ 'type1': '231', // `type`: `sum(amount)` 'type2': '543' ] } 我将选择用户阵列,因此我需要急切地加载它。我应该如何为这写一

我有两种型号:
用户
交易
,带有
用户id
类型
,以及
金额
字段。我希望能够选择具有按类型分组的事务数组的用户,如下所示:

{ // User instance 
    'id': 123,
    'username': 'John'
    'transactions': [
        'type1': '231', // `type`: `sum(amount)`
        'type2': '543'
    ]
}
我将选择用户阵列,因此我需要急切地加载它。我应该如何为这写一个雄辩的模型?我已经阅读了所有文档,但仍然不知道如何处理此问题。

您可以尝试以下方法:

  $column = [DB::raw('SUM(order_qty) as volume'),
            DB::raw('SUM(order_qty*price) as value')];
 $oldValueVolume = OrderProduct::select($column)
                    ->where('order_id', $ordersId)
                    ->first();
因此,电话:

User::with(
    [
        'transactions' => function ($q) {
            return $q->groupBy(['type', 'user_id'])
                     ->selectRaw('sum(amount) as sum, type, user_id');
        }
    ]
)->get();
注释

  • 我使用“with”表示急切加载
  • 您在问题中提到了自定义结构(对):
  • 这部分

    'transactions': [
        'type1': '231', // `type`: `sum(amount)`
        'type2': '543'
    ]
    

    默认情况下,这不是Eloquent所做的,而是。

    当您进行求和(金额)时,哪些交易取为求和?其中
    transaction.user\u id=user.id
    ,按
    user\u id
    type
    分组,您回答的问题是什么?那些栏目是什么?
    'transactions': [
        'type1': '231', // `type`: `sum(amount)`
        'type2': '543'
    ]