Return 具有数据透视字段的数据 Laravel Api

Return data with pivot field Laravel Api

我想 return 一个具有它权限的角色通过 pivot table,关系,但是当我写:

$role = $this->roleRepository->detail($id);
    $data = ([
        "role" => $role
    ]);

邮递员刚刚return:

"data": {
        "role": {
            "id": 12,
            "name": "grand-admin"
        }
    }

我写:

        $role = $this->roleRepository->detail($id);
        $data = ([
            "role" => $role,
            "hasPermission" => $role->permissions
        ]);

邮递员return:

"data": {
        "role": {
            "id": 12,
            "name": "grand-admin",
            "permissions": [
                {
                    "id": 1,
                    "name": "view_customer",
                    "pivot": {
                        "role_id": 12,
                        "permission_id": 1
                    }
                },
                {
                    "id": 1,
                    "name": "view_customer",
                    "pivot": {
                        "role_id": 12,
                        "permission_id": 1
                    }
                }
            ]
        },
        "hasPermission": [
            {
                "id": 1,
                "name": "view_customer",
                "pivot": {
                    "role_id": 12,
                    "permission_id": 1
                }
            },
            {
                "id": 1,
                "name": "view_customer",
                "pivot": {
                    "role_id": 12,
                    "permission_id": 1
                }
            }
        ]
    }

问题是循环2次权限数据,我怎么能只写return上半部分。

您可以在存储库逻辑中包含关系(使用 with),或者您可以 lazy-load 像这样的关系:

$role = $this->roleRepository->detail($id);
$role->load('permissions');
$data = ([
    "role" => $role
]);

延迟加载参考: https://laravel.com/docs/9.x/eloquent-relationships#lazy-eager-loading

您可以通过在模型中定义 $with 属性 将 permissions 作为默认加载关系包括在内:

//your role model
class Role extends Model
{
    protected $with = ['permissions'];
...
}

现在您现有的代码应该包含权限。

默认加载参考:https://laravel.com/docs/9.x/eloquent-relationships#eager-loading-by-default