我正在开发一个使用 Laravel 构建的应用程序,在后端我有一些雄辩的 2 个表之间的多对多关系,主要分别是角色和权限。还有一个名为 role_permission 的数据透视表。我在模型中创建了关系,并且在控制器中捕获以下值以创建权限:name, description , slug, role_id。在逻辑上,将名称、描述和 slug 存储在权限表中,而 role_id 存储在数据透视表 (role_permission) 中。这工作正常。在响应中,我获取存储在权限表中的所有权限并显示为 JSON 对象。问题是我想获取数据透视表中的 role_id 并附加到显示为响应的每个 JSON 对象。榜样<?phpnamespace Modules\API\Entities;use Modules\API\Entities\Permission;use Illuminate\Database\Eloquent\Model;class Role extends Model{ protected $fillable = ['name' , 'slug' , 'description']; /** * A role has more than one permission */ public function permissions(){ return $this->belongsToMany(Permission::class , 'role_permission'); }}权限模型<?phpnamespace Modules\API\Entities;use Modules\API\Entities\Role;use Illuminate\Database\Eloquent\Model;class Permission extends Model{ protected $fillable = ['name' , 'slug' , 'description']; /** * A permission has more than one role */ public function roles(){ return $this->belongsToMany(Role::class , 'role_permission'); }}上述逻辑后 POSTMAN 中的示例响应{ "request_time": "2019-09-03 07:54:54", "response_time": "2019-09-03 07:54:54", "status": "success", "message": "Permision Successfully added", "data": [ { "id": 1, "name": "Create Post", "slug": "craete-post", "description": "mnmnmn" }, { "id": 3, "name": "delete User", "slug": "del-user", "description": "mnmnmn" }, { "id": 5, "name": "Create User", "slug": "create-user", "description": "mnmnmn" } ]}
1 回答
慕村225694
TA贡献1880条经验 获得超4个赞
尝试改变:
$permissions = Permission::select('id' , 'name', 'slug', 'description')->get()->toArray();
进入:
$permissions = Permission::select('id' , 'name', 'slug', 'description')->with('roles')->get()->toArray();
$mappedPermissions = array_map(function ($permission) {
$permission['role_id'] = data_get($permission, '0.pivot.role_id');
unset($permission['roles']);
return $permission;
}, $permissions);
// Then use the $mappedPermissions from here on.
- 1 回答
- 0 关注
- 121 浏览
添加回答
举报
0/150
提交
取消