【问题标题】:Property [roles] does not exist on this collection instance此集合实例上不存在属性 [角色]
【发布时间】: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');
    }

请指教我哪里做错了?谢谢!

【问题讨论】:

  • 这是因为你的关系包含一个数组。您必须遍历您的角色关系,然后访问角色名称
  • $accounts is 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}}]

标签: laravel eloquent


【解决方案1】:

@junmingyeo98 能否请将 Account.php 中的关联函数从 belongsToMany 更改为 belongsTo。

【讨论】:

  • 我已经按照建议进行了更改,但是我现在收到此错误Trying to get property 'roleName' of non-object
  • 你也可以像下面这样改变你的查询,$accounts = Account::with('roles')->where('acc_clinicID', \Session::get('clinic_ID'))->获取();
  • 您好,我已经尝试了您的建议,结果相同。
  • 你好@junmingyeo98,我刚刚检查了你的dd结果,发现角色在数组中,所以我希望你正在尝试访问foerach循环。谢谢:)
  • 嗨,我确实为此包含了一个 foreach 循环,如下所示,但是一旦我将$account->roles->roleName 添加到我的$account->roles 中,就会显示属性错误。 @foreach($accounts as $account) <tr id="{{ $account->{'accountID'} }}"> <td></td> <td>{{ $account->{'name'} }}</td> <td>{{ $account->{'username'} }}</td> <td>{{ $account->{'email'} }}</td> <td>{{ $account->{'phoneNo'} }}</td> <td>{{ $account->roles }}</td> </tr> @endforeach
猜你喜欢
  • 2020-11-22
  • 2020-11-12
  • 2019-03-23
  • 2020-07-11
  • 2017-05-12
  • 2018-10-12
  • 2021-02-08
  • 2021-12-16
相关资源
最近更新 更多