【问题标题】:Laravel: using lists() to include childrenLaravel:使用列表()包含孩子
【发布时间】:2016-05-10 00:57:58
【问题描述】:

我有一个查询输出如下内容:

{"id":1,"name":"Text1","parent_id":"0","created_at":"2016-04-27 02:28:45","updated_at":"-0001-11-30 00:00:00","children":[{"id":19,"name":"Text2","parent_id":"1","created_at":"2016-04-29 18:04:14","updated_at":"-0001-11-30 00:00:00","children":[{"id":2,"name":"Text3","parent_id":"19","created_at":"2016-04-27 02:28:45","updated_at":"-0001-11-30 00:00:00","儿童":[]}]}]}

请注意,返回的每个项目都有一个 children 属性,该属性返回与该项目相关的所有子项。

我需要能够获得所有id 的列表,包括children 下的列表。

在这种情况下,我需要它来简单地输出:

[1, 19, 2]

我该怎么做?

【问题讨论】:

  • 不适用于lists。您可能需要通过它foreach
  • 假设这个查询类似于Model::all()->with('children'),然后您可以对该查询执行->lists('id'),它应该为您提供所有ID,包括children
  • @Ohgodwhy 它只返回顶级项目,而不是子项。 ://
  • 请问您使用的查询是什么?
  • Post::all()->with('children')

标签: php laravel laravel-5 laravel-5.2


【解决方案1】:

以下应该有效:

$parent = Parent::all();

// L5
$children = $parent->children->lists('id');

// L5.1
$children = $parent->children->lists('id')->all();

// L5.2
$children = $parent->children->pluck('id');

【讨论】:

    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多