简体   繁体   English

Laravel - 如何从嵌套关系中提取字段

[英]Laravel - How to pluck field from nested relations

I'm trying to pluck field from nested relations.我正在尝试从嵌套关系中提取字段。

My class structure is:我的 class 结构是:

User      hasMany       GroupUser
GroupUser belongsTo     Group
Group     belongsToMany Promotion

So this way I can get fine get Promotions from an User所以这样我就可以很好地从用户那里获得促销

$user->groupUsers()->with('group')->with('group.promotions')->get();

{
  "id": 4,
  ....
  "promotions": [
    {
      "id": 3,
      "group_id": 11,
      "user_id": 4,
      ...
      "group": {
        "id": 11,
        ...
        "promotions": [
          {
            "id": 8,
            "title": "Lavagem Mensal 1 unid.",
            "const": "LAVAGEM_MENSAL1_UNID",
            "pivot": {
              "group_id": 11,
              "promotion_id": 8
            }
          }
        ]
      }
    }
  ]
}

So what I need is to get a pluck list of Promotions.const .所以我需要的是获取Promotions.const的采摘清单。

Tried this way but it returns [null]尝试过这种方式,但它返回[null]

$user->groupUsers()->with('group')->with('group.promotions')->get()->pluck('group.promotions.const');

UPDATE: Now this way I close to achieve it.更新:现在我通过这种方式接近实现它。

$user->groupUsers()->with('group')->with('group.promotions')->get()->pluck('group.promotions.*.const');

"promotions": [
  [
    "BRF_LAVAGEM_MENSAL_1_UNID"
  ]
]

Just need to flat this array.只需要展平这个数组。

Try this:尝试这个:

$user->groupUsers()
    ->with('group.promotions')
    ->get()
    ->pluck('group.promotions.*.const')
    ->collapse();

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

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