【问题标题】:Laravel collection: return only relationship and keyLaravel 集合:仅返回关系和键
【发布时间】:2018-02-12 17:20:45
【问题描述】:

我有一个类似这样的集合:

$a = Model::with(['sub' => function($q) {
    $q->select('id', 'name')
}])->get();

这将返回以下集合:

{
    0: {
        id: 0001,
        name: "item 1",
        type: "type a"
        'sub' [
            {
                'id': 10001,
                'name': "sub Item 1"
            },
            {
                'id': 10002,
                'name': "sub Item 2"
            }
        ]
    },
    1: {
        id: 0002,
        name: "item 2",
        type: "type a"
        'sub' [
            {
                'id': 11001,
                'name': "sub Item 4"
            },
            {
                'id': 11002,
                'name': "sub Item 5"
            }
        ]
    }

我想要做的是通过它们的 id 来键入父项,并且只返回关系。例如

{
    0001: {
        'sub' [
            {
                'id': 10001,
                'name': "sub Item 1"
            },
            {
                'id': 10002,
                'name': "sub Item 2"
            }
        ]
    },
    0002: {
        'sub' [
            {
                'id': 11001,
                'name': "sub Item 4"
            },
            {
                'id': 11002,
                'name': "sub Item 5"
            }
        ]
    }

我似乎无法让它工作。我尝试了很多变体,包括:

$a = Model::with(['sub' => function($q) {
    $q->select('id', 'name')
}])->pluck('sub', 'id');

这不起作用,因为“Pluck”显然是在寻找一个名为“sub”的父模型的属性,它不会退出。有没有办法做到这一点?

谢谢

【问题讨论】:

    标签: laravel collections pluck


    【解决方案1】:

    使用 keyBy 将您的 pk 用作数组索引。 https://laravel.com/docs/5.4/collections#method-keyby

    但是忽略其他字段,您可能需要eachfilter。选择Sub::where(...)然后在parent_id上使用集合groupBy不是更容易吗:https://laravel.com/docs/5.4/collections#method-groupby

    比如Sub::where(...)->get()->groupBy('parent_id')

    【讨论】:

      【解决方案2】:

      你快到了。您需要在pluck() 之前执行->get()

      $a = Model::with([
          'sub' => function ($q) {
              $q->select('id', 'name');
          },
      ])->get()->pluck('sub', 'id');
      

      您的示例中使用的pluck() 将是pluck 的查询构建器版本,而不是集合版本。

      【讨论】:

      • 此解决方案不会在结果中保留键“sub”。但是,在我的实际情况下,这不是问题。谢谢
      • @Typhoon101 你用的是什么版本的 Laravel?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-03
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      • 2020-02-02
      • 2021-09-08
      相关资源
      最近更新 更多