我正在尝试在 Eloquent 中加入 3 个表,即用户、部门和角色。一个用户只能有一个部门和一个角色。以下是我定义模型的方式:
用户模型:
public function department(){
return $this->has_one('Department', 'department_id');
}
public function role(){
return $this->has_one('Role', 'role_id');
}
}
部
<?php
class Department extends Eloquent
{
public static $key = 'department_id';
public static $table = 'sys_departments';
public static $timestamps = false;
public function user(){
return $this->belongs_to('User', 'user_id');
}
}
角色
class Role extends Eloquent
{
public static $key = 'role_id';
public static $table = 'sys_roles';
public static $timestamps = false;
public function user(){
return $this->belongs_to('User', 'user_id');
}
public function transaction(){
return $this->has_many('Transaction', 'transaction_id');
}
}
这是我在控制器中访问它们的方式:
$user = User::with(array('department', 'role'))->where('user_id', '=', 1)->first();
echo $user->department->department;
它正在产生这些查询:
SELECT * FROM `tbl_users` WHERE `user_id` = '1' LIMIT 1
SELECT * FROM `tbl_users` WHERE `user_id` = '1' LIMIT 1
SELECT * FROM `sys_departments` WHERE `department_id` IN ('1')
SELECT * FROM `sys_roles` WHERE `role_id` IN ('1')
有任何想法吗?