Laravel当我尝试访问类中的函数时调用未定义的方法

问题描述 投票:0回答:1

在laravel上实现ACL后,我想使用sync为用户附加一些权限,当我尝试使用此代码时:

Route::get('/setPermission', function () {
    //auth()->loginUsingId(1);

    return \App\Role::whereName('admin')->permissions()->sync(
        [
            1, 2
        ]
    );
});

我收到此错误:

"Call to undefined method Illuminate\Database\Query\Builder::permissions()"

我的Role课程:

class Role extends Model{
    protected $fillable = ['name','label'];

    public function users(){
        return $this->belongsToMany(User::class);
    }

    public function permissions(){
        return $this->belongsToMany(Permission::class);
    }
}

Permission类:

class Permission extends Model{
    protected $fillable = ['name','label'];

    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}

获得用户Roles的结果:

[{"id":2,"name":"admin","label":"\u0645\u062f\u06cc\u0631 \u06a9\u0644 \u0633\u0627\u06cc\u062a \u0648 \u0633\u06cc\u0633\u062a\u0645","created_at":"2017-12-21 07:44:09","updated_at":"2017-12-21 07:44:09"}]
laravel laravel-5
1个回答
0
投票

此代码解决了问题:

->first()之后加入whereName

Route::get('/setPermission', function () {
    //auth()->loginUsingId(1);

    return \App\Role::whereName('admin')->first()->permissions()->sync(
        [
            1, 2
        ]
    );
});
© www.soinside.com 2019 - 2024. All rights reserved.