我正在使用https://github.com/jenssegers/Laravel-MongoDB作为后端,使用Laravel 4和MongoDB实现身份验证。
我的用户模型是这样的:
use Illuminate\Auth\UserInterface;
/**
* Class User
* @property string $username
* @property string $password
*/
class User extends Moloquent implements UserInterface {
/**
* Primary key for collection
*
* @var string
*/
protected $primaryKey = 'username';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password');
/**
* Relationship with role
*
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function role() {
return $this->belongsTo('Role');
}
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->username;
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the token value for the "remember me" session.
*
* @return string
*/
public function getRememberToken()
{
return $this->remember_token;
}
/**
* Set the token value for the "remember me" session.
*
* @param string $value
* @return void
*/
public function setRememberToken($value)
{
$this->remember_token = $value;
}
/**
* Get the column name for the "remember me" token.
*
* @return string
*/
public function getRememberTokenName()
{
return 'remember_token';
}
}
这是我的角色模型:
/**
* Class Role
* @property string name
*/
class Role extends Moloquent {
/**
* Primary key for collection
*
* @var string
*/
protected $primaryKey = 'name';
/**
* Collection name for role
*
* @var string
*/
protected $collection = 'roles';
/**
* Relationship with users
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users() {
return $this->belongsToMany('User');
}
}
如您所见,我的用户只有username
和password
,角色只有name
。
$user->role()->save($role)
或attach
而不是save
,但只有$role->users()->save($user)
才能正常工作。为什么?难道他们都不能工作吗?我似乎不太了解Laravel的关系概念。
另一件事是如何获得用户的角色?例如:
$user = Auth::user();
var_dump($user->role()->get());
给出一个空集合。不应该给我用户的作用吗?
我很困惑!
提前谢谢。
编辑:这是我的播种:
class RoleTableSeeder extends Seeder {
public function run() {
$adminRole = Role::where('name', 'admin')->first();
if(empty($adminRole)) {
Role::create(array(
'name' => 'admin',
));
Role::create(array(
'name' => 'superuser',
));
Role::create(array(
'name' => 'user',
));
}
}
}
class UserTableSeeder extends Seeder {
public function run() {
$admin = User::where('name', 'admin')->first();
if(empty($admin)) {
$role = Role::where('name', 'admin')->first();
$admin = new User();
$admin->username = 'admin';
$admin->password = Hash::make('adminP@%%');
$admin->save();
$role->users()->attach($admin);
}
}
}
答案 0 :(得分:0)
我不确定为什么保存角色不起作用也许您可以提供更多信息,但您也可以尝试$user->role()->create($role).
但请确保$ role是一个雄辩的对象。
获取用户角色时,您应该使用$user->roles