【发布时间】:2019-02-12 19:38:46
【问题描述】:
我的应用基于
Laravel: 5.6.35
PHP 7.2.4
Entrust: 1.9
我的榜样
class Role extends EntrustRole
{
public function permissions()
{
return $this->belongsToMany(Permission::class);
}
public function users()
{
return $this->hasMany(User::class);
}
}
我的用户模型是
class User extends Authenticatable
{
public function role()
{
return $this->belongsTo(Role::class);
}
}
现在你可以在 Tinker 中注意到了
D:\work\www\myapp>php artisan tinker
Psy Shell v0.9.7 (PHP 7.2.4 — cli) by Justin Hileman
>>> App\models\Role::find(1)->users()->get()
Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.role_id' in 'where clause' (SQL: select * from `users` where `users`.`role_id` = 1 and `users`.`role_id` is not null)'
>>> App\User::find(1)->role()->get();
=> Illuminate\Database\Eloquent\Collection {#2937
all: [],
}
>>> App\User::find(1)->roles()->get();
=> Illuminate\Database\Eloquent\Collection {#2941
all: [
App\models\Role {#2930
id: 1,
name: "super-admin",
display_name: "Super Admin",
description: "This will be one permission, that can not be assigned or modified.",
created_at: "2018-09-07 12:11:35",
updated_at: "2018-09-07 12:11:35",
pivot: Illuminate\Database\Eloquent\Relations\Pivot {#2927
user_id: 1,
role_id: 1,
},
},
],
}
我得到了App\User::find(1)->roles() 的结果,但我的用户模型有函数role(),App\User::find(1)->role() 的集合为空,App\models\Role::find(1)->users() 的错误为
所以请给一些想法,如何解决这个问题?
【问题讨论】:
-
如果角色给出结果,为什么不简单地将角色更改为用户模型中的角色。
-
您的用户表中有字段“role_id”吗?
-
@CarlosSalazar 没有,但他们是另一个维护 role_user 关系的表。
标签: php laravel eloquent entrust eloquent-relationship