简体   繁体   English

如何构建这个 Laravel Eloquent Query

[英]How to build this Laravel Eloquent Query

I want to build a nested array from a simple table with Laravel Eloquent, but i couldn't.我想用 Laravel Eloquent 从一个简单的表构建一个嵌套数组,但我不能。

So basically below is a snap shot of my table所以基本上下面是我桌子的快照

在此处输入图片说明

and this is the array I want to build这是我要构建的数组

在此处输入图片说明

You can use some methods from collection :您可以使用集合中的一些方法:

$result = $data->groupBy(['market_id', 'base_currency', 'currency_id'])
    ->map(function ($item) {
        return $item->map(function ($item) {
            return $item->map(function ($item) {
                return $item->map(function ($item) {
                    return $item['currency_id'];
                });
            })->flatten();
        })->sortKeys();
    });

dd($result->toArray());
array:1 [
  1 => array:2 [
    1 => array:2 [
      0 => 2
      1 => 3
    ]
    2 => array:2 [
      0 => 1
      1 => 2
    ]
  ]
]

Explanation解释

groupBy

The groupBy method groups the collection's items by a given key. groupBy方法按给定的键对集合的项目进行分组。 Multiple grouping criteria may be passed as an array.多个分组标准可以作为数组传递。 Each array element will be applied to the corresponding level within a multi-dimensional array:每个数组元素将应用于多维数组中的相应级别:

$data->groupBy(['market_id', 'base_currency', 'currency_id']);

map

The map method iterates through the collection and passes each value to the given callback. map方法遍历集合并将每个值传递给给定的回调。

->map(function ($item) {
    return $item;
});

flatten

The flatten method flattens a multi-dimensional collection into a single dimension: flatten方法将多维集合flatten平为单维:

->flatten()

sortKeys

The sortKeys method sorts the collection by the keys of the underlying associative array: sortKeys方法按底层关联数组的键对集合进行排序:

->sortKeys()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM