【发布时间】:2015-03-17 00:46:15
【问题描述】:
我正在使用 Laravel 4 和 MongoDB 实现身份验证,使用 https://github.com/jenssegers/Laravel-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。
问题是,如何保存相关模型?我尝试了很多方法,就像在 Laravel Eloqoent 文档中一样,比如 $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);
}
}
}
【问题讨论】:
标签: php mongodb authentication laravel