【问题标题】:How to build this Laravel Eloquent Query如何构建这个 Laravel Eloquent 查询
【发布时间】:2020-02-17 15:18:19
【问题描述】:

我想用 Laravel Eloquent 从一个简单的表构建一个嵌套数组,但我做不到。

所以基本上下面是我的桌子的快照

这是我要构建的数组

【问题讨论】:

  • 结果是什么(错误信息)?

标签: php database laravel eloquent


【解决方案1】:

你可以使用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
    ]
  ]
]

说明

groupBy

groupBy 方法按给定键对集合的项目进行分组。多个分组标准可以作为数组传递。每个数组元素都将应用于多维数组中的相应级别:

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

map

map 方法遍历集合并将每个值传递给给定的回调。

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

flatten

flatten 方法将多维集合扁平化为一个维度:

->flatten()

sortKeys

sortKeys 方法通过底层关联数组的键对集合进行排序:

->sortKeys()

【讨论】:

    猜你喜欢
    • 2021-08-17
    • 2021-12-26
    • 2020-03-19
    • 1970-01-01
    • 2018-10-27
    • 2016-03-30
    • 2016-02-09
    • 2020-07-18
    • 2019-09-21
    相关资源
    最近更新 更多