【问题标题】:Eloquent, use pluck() to filter a deep collectionEloquent,使用 pluck() 过滤深层集合
【发布时间】:2020-04-25 22:59:00
【问题描述】:

我只需要返回具有权限name 列的数组,但不能使其与->pluck() 一起使用

class User
{
public function roleTeams()
    {
        return $this->hasMany(RoleTeam::class);
    }
}
class RoleTeams
{
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}
class Role
{
    public function permissions()
    {
        return $this->belongsToMany(Permission::class);
    }
}

这是我根据找到的类似答案尝试的最后一个代码。

$permissions = $user->roleTeams()->with('roles.permissions')->pluck('roles.*.permissions.*.name')->all();

预期的结果是

[
    'edit_user',
    'delete_user',
    ...
]

【问题讨论】:

  • 这没有任何意义,所有的关系都工作正常,我的问题是只返回一个包含 permissions.name 列内容的数组。
  • 用它来通过另一个关系访问一个关系。在您的情况下,它可能行不通,因为您有 3 个分支关系而不是 2 个。也许您应该重新考虑您的设计。
  • 它与公认的答案完美配合,无论如何感谢您的时间:)

标签: database laravel eloquent


【解决方案1】:

所以,我试图模拟你的情况。我的代码是:

$arr = [
    'id'    => 1,
    'name'  => 'User 1',
    'roles' => [
        [
            'id'          => 2,
            'name'        => 'Admin',
            'permissions' => [
                [
                    'id'   => 8,
                    'name' => 'edit_user',
                    'type' => 'editor',
                ],
                [
                    'id'   => 9,
                    'name' => 'delete_user',
                    'type' => 'deleter',
                ],
            ],
        ],
        [
            'id'          => 3,
            'name'        => 'Manager',
            'permissions' => [
                [
                    'id'   => 6,
                    'name' => 'do_smth1_with_user',
                    'type' => 'smth1',
                ],
                [
                    'id'   => 7,
                    'name' => 'do_smth2_with_user',
                    'type' => 'smth2',
                ],
            ],
        ],
    ],
];

$collection = collect([$arr]);

并且有感兴趣的结果。如果在您的答案中使用pluck() 方法:

dd($collection->pluck('roles.*.permissions.*.name'));

结果会是这样的:

Collection {#322 ▼
  #items: array:1 [▼
    0 => array:4 [▼
      0 => "edit_user"
      1 => "delete_user"
      2 => "do_smth1_with_user"
      3 => "do_smth2_with_user"
    ]
  ]
}

但如果我使用 pluck()collapse() 方法,它看起来像你想要的:

dd($collection->pluck('roles')->collapse()->pluck('permissions')->collapse()->pluck('name'));

结果是:

Collection {#322 ▼
  #items: array:4 [▼
    0 => "edit_user"
    1 => "delete_user"
    2 => "do_smth1_with_user"
    3 => "do_smth2_with_user"
  ]
}

老实说,我不知道为什么它会像它一样有效,但请尝试将它与 collapse() 方法一起使用,如果它对您有帮助,请告诉我。 希望我的回答能帮助您解决问题。

【讨论】:

  • 谢谢,效果很好,但是是的,由于某种原因 -pluck('roles.*.permissions.*.name') 重新调整了双数组
  • 很好。很高兴它有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-22
  • 1970-01-01
  • 2017-04-12
相关资源
最近更新 更多