【发布时间】:2021-03-25 06:26:17
【问题描述】:
我目前有帐户表、角色表和帐户角色表,它们存储关系的帐户 ID 和角色 ID。我正在尝试通过检查 AccountRoles 表中标记为帐户 ID 的 ID 从角色表中获取角色名称。
下面是我的控制器代码:
$accounts = Account::with('roles')->where('acc_clinicID', '=', $_SESSION['clinic_ID'])->get();
我尝试了 dd($accounts) 并且能够从图像中附加的关系中获取角色名称。 dd($accounts) result
但是,当我执行 dd($accounts->roles->roleName) 时,我得到了错误:Property [roles] does not exist on this collection instance。
以下是我所涉及的表的模型:
帐户.php
public function roles()
{
return $this->belongsToMany('App\Models\Role');
}
角色.php
public function accounts()
{
return $this->hasMany('App\Models\Account');
}
请指教我哪里做错了?谢谢!
【问题讨论】:
-
这是因为你的关系包含一个数组。您必须遍历您的角色关系,然后访问角色名称
-
$accountsis a Collection ...get在 Builder 上总是返回一个 Collection -
是的,我正在尝试显示具有该帐户在数据表中标记的角色的帐户列表,因此我使用
get返回一个集合 -
@AhmadKarimi 我在我的 foreach 循环的前端尝试了
$account->roles->roleName,它给出了Property [roleName] does not exist on this collection instance.的错误 -
我在前端尝试了
$account->roles我能够在我的每一行数据表中获取这些数据[{"roleID":1,"roleName":"Admin","created_at":"2021-03-25T05:57:54.000000Z","updated_at":"2021-03-25T05:57:54.000000Z","pivot":{"account_accountID":1,"role_roleID":1}}]