laravel模型关系结果

时间:2018-12-31 11:06:30

标签: laravel collections model

admin_rolesadmin_permissions表是多对多关系

admin_permission中查询ID,其中admin_roles的ID为1,2

使用SQL实现:

SELECT
    DISTINCT`admin_role_permissions`.permission_id
FROM
    `admin_permissions`
INNER JOIN `admin_role_permissions` ON `admin_permissions`.`id` = 
    `admin_role_permissions`.`permission_id`
WHERE
   `admin_role_permissions`.`role_id` IN (1, 2)

结果:

  

$ permission_ids = [1,3,4 ....];

如何使用laravel模型达到上述效果?

AdminRoleController.php

$role_ids = ['1','2'];
$permissions = AdminRole::with('relPermission')->whereIn('id', $role_ids)->get();

AdminRole.php

public function relPermission(){
    return $this->belongsToMany('App\Model\AdminPermission', 'admin_role_permissions', 'role_id', 'permission_id');
}

但是结果:

enter image description here

如何获得类似的结果

  

$ permission_ids = [1,3,4 .....]

使用laravel模型或laravel集合

1 个答案:

答案 0 :(得分:1)

您可以使用pluck方法:

$permissions = AdminRole::with('relPermission')->whereIn('id', $role_ids)->pluck('rel_permission.id');