我正尝试与2个模型User
和Role
创建一对多关系。所以,我希望那一个User
只能有一个角色,并且Role
可以被分配到多于User
。我试图按照官方教程https://laravel.com/docs/5.1/eloquent-relationships#one-to-many,并结束了与此:一对多关系不起作用
class User extends Model
{
public function role()
{
return $this->belongsToMany('App\Admin\Role');
}
}
class Role extends Model
{
protected $table = 'roles';
public function users()
{
return $this->hasMany('App\Admin\User');
}
}
基于该链接的,我觉得Role
是同样的事情Post
,一个Role
可以分配给许多User
。然而,这完全不是那么回事,这里就是我想对特定User
$role_first = $user->role; // Eloquent\Collection
$role_second = $user->role(); // Eloquent\Relations\BelongsToMany
$role_first->role_title // 'Undefined property: Illuminate\Database\Eloquent\Collection::$role_title'
$role_second->role_title // exception 'ErrorException' with message 'Undefined property: Illuminate\Database\Eloquent\Relations\BelongsToMany::$role_title'
访问角色名称究竟是什么错在这里?
您在此处创建了一对一关系(hasOne和belongsTo),这是不正确的。许多用户可以具有相同的角色,这是一对多的关系。 –