laravel关系一对一或一对多?

时间:2014-09-25 14:36:14

标签: php laravel laravel-4

表1(用户):

id    username   password  role created_at updated_at

1      jhon        yz        1   sometime     sometime

表2(角色):

id     role     created_at   updated_at

1    employee     sometime    sometime

我想要什么

id    username   password  role     created_at updated_at

1      jhon        yz     employee   sometime     sometime

用户型号:

class User extends Eloquent implements UserInterface, RemindableInterface {
    public function role()
    {
        return $this->hasOne('role', 'id', 'role');
    }
    protected $table = 'users';
    protected $hidden = array('password', 'remember_token');    
}

角色模型:

class Role extends Eloquent {
    protected $table = 'roles'; 
}

如何在视图中获取角色名称?我的关系是对的吗

1 个答案:

答案 0 :(得分:0)

许多用户可以使用一个角色,例如:

user1可以是管理员 user2也可以是管理员 user3是一名经理 user4也是一名经理

如果那样的话,那么......

用户型号:

    class User extends Eloquent implements UserInterface, RemindableInterface {
        protected $table = 'users';
        protected $hidden = array('password', 'remember_token');

        public function role()
        {
            return $this->belongsTo('Role');
        }
    }

角色模型:

class Role extends Eloquent {
    protected $table = 'roles';

    public function users()
    {
        return $this->hasMany('User');
    }
}

然后使用:

User::with('role')->whereRole(1)->get(); // assuming that 1 = employee; this is eager loading

这会产生类似的结果:

[
    new User([
       'id' => 1,
       'username' => 'blahblah',
       'password' => 'pass',
       'role' => 1,
       'created_at' => '0000-00-00',
       'updated_at' => '0000-00-00',
       'role' => new Role([
                    'id' => 1,
                    'role' => 'employee',
                    'created_at' => '0000-00-00',
                    'updated_at' => '0000-00-00'
                 ])
    ])
]