【问题标题】:Method Illuminate\Database\Eloquent\Collection::hasRole does not exist. Laravel [closed]方法 Illuminate\Database\Eloquent\Collection::hasRole 不存在。 Laravel [关闭]
【发布时间】:2019-08-29 19:26:48
【问题描述】:

我在我的 laravel 项目中使用 Zizaco/entrust 角色,我想按目标 ID 为用户使用下拉列表,并且用户具有角色员工。 错误

方法 Illuminate\Database\Eloquent\Collection::hasRole 没有 存在。

public function show($id)
{
$users_list = User::all();
        $asiTo=Contracts::find($id)
        ->where('contracts.id',$id)
        ->join('users','contracts.condesid','users.des_id')
        ->join('roles','users.id',$users_list->hasRole('staff'))
        ->select('users.*')
        ->get();
return view('admin.contracts.show', compact('asiTo'));
}

用户类

class User extends Authenticatable
{
    use Notifiable, EntrustUserTrait;
    public function role()
    {
        return $this->hasOne('App\Role');
    }
}

角色类

class Role extends EntrustRole
{
    public function user()
        {
            return $this->belongsTo(User::class);
        }
}

刀片:

 <select class="form-control custom-select-value" name="assigto" required="required">
 <option value="">Select User </option>
          @foreach($asiTo as $user)
          <option value="{{$user->id}}"> {{$user->name}}</option>
           @endforeach

   </select>

【问题讨论】:

  • 您的查询在哪里结束?没有;
  • 你能更详细地解释一下这段代码的作用吗?
  • @Jerodev 对不起,我更新了问题
  • 此问题与同一用户的another question密切相关。
  • @JorisJ1 是的,这是我的问题,我还没有找到解决办法

标签: php laravel


【解决方案1】:

您不能通过连接使用hasRole() 方法。仅当您已将 EntrustUserTrait 特征添加到相关模型时,您才能访问此方法。

仔细查看 zizaco/entrust 包的 the exampleUser 模型使用了 EntrustUserTrait 特征,之后您可以访问 roles(), hasRole() 等。

要访问hasRole(),请设置Eloquent 关系

https://laravel.com/docs/5.8/eloquent-relationships

【讨论】:

  • 谢谢你的评论,我建立了关系,不能像-&gt;join('roles',function($join){ $join-&gt;where(User::hasRole('staff')); })那样使用hasrole
【解决方案2】:

当您运行User::all() 时,您会返回一个 Eloquent 集合,而不是模型的实例。 hasRole 方法在模型上,这就是您收到错误的原因。

entrust 包有一个您可以使用的查询范围,以便您可以获取具有特定角色的所有用户。为此,您可以将代码更改为以下内容:

$users_list = User::withRole('staff')->get();

那应该只返回那些具有staff 角色的用户。

【讨论】:

  • 感谢您的回答能否告诉我如何将此代码与join 代码集成
【解决方案3】:

使用where()前请加入表

【讨论】:

  • 我尝试使用$users_list = User::withRole('staff') -&gt;join('contracts','contracts.id',$id) -&gt;join('users','contracts.condesid','users.des_id') -&gt;select('users.*') -&gt;get(); 但不起作用
  • 你可以使用$users_list = User::join('contracts','contracts.id','=',$id) -&gt;join('users','contracts.condesid','users.des_id') -&gt;select('users.*','contracts.*') where('role_col','staff')-&gt;get();
  • SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'users' (SQL: select users.* from users` 内部联接contracts on contracts.id = 11 内部联接users on @9876543@30@.@987654333 @.des_id 其中role_col = 员工)`
  • 能分享一下型号和功能吗
  • 我更新问题
猜你喜欢
  • 2020-01-25
  • 2022-01-10
  • 2021-03-26
  • 1970-01-01
  • 2021-05-30
  • 2020-03-25
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
相关资源
最近更新 更多