【问题标题】:Get array of Models from a laravel collection从 laravel 集合中获取模型数组
【发布时间】:2016-12-11 00:22:40
【问题描述】:

给定 Eloquent ModelsCollection,它们是 Arrayable,我怎样才能获得这些对象的数组?

如果我在集合上调用 ->toArray(),它会给我一个嵌套的关联数组,从而破坏模型。

如果我将它转换为一个数组,我会得到这个非常奇怪的东西:

array:1 [▼
  "\x00*\x00items" => array:1 [▼
    "temp" => HistorySeries {#374 ▼
      #table: "history_series_hse"
      #primaryKey: "id_hse"
      #connection: "mysql"
      +timestamps: false
      <...snip...>
    }
  ]
]

然后是这个,但我不是很喜欢它(它有效):

    $reflection = new ReflectionClass($coll);
    $property = $reflection->getProperty('items');
    $property->setAccessible(true);
    $array = $property->getValue($coll);

或者我可以使用 foreach 循环提取它,但这很难看。有什么好办法吗?

【问题讨论】:

  • 试试$collection-&gt;all()?
  • 你试过each()方法吗?

标签: php arrays laravel


【解决方案1】:

不要尝试强制转换为数组,而是让您的 Collection 保持完整,并使用像 mapeach 这样的高阶函数来做您需要做的事情。

例如:

$multiplied = $collection->map(function ($item, $key) {
    return $item * 2;
});

$multiplied->all();

您没有指定实际需要对数据做什么,所以这只是一个松散的示例from the docs

您不能强制转换为数组并保持模型完整,它不会工作。

【讨论】:

  • "你不能得到一个数组并保持模型完整,它是行不通的。"这是不正确的。从模型集合中获取模型数组是完全可能的。
  • 我意识到这不是我想说的。
【解决方案2】:

Collection 只是标准数组的包装器。要获取该标准数组,请在 Collection 上调用 all() 方法。

// Collection of Item models
$itemsCollection = Item::all();

// standard array of Item models
$itemsArray = $itemsCollection->all();

【讨论】:

    猜你喜欢
    • 2014-03-23
    • 2016-11-19
    • 1970-01-01
    • 2019-01-28
    • 2013-08-08
    • 2016-07-10
    • 1970-01-01
    • 2017-05-30
    • 2011-11-28
    相关资源
    最近更新 更多