I'm trying to join 3 tables in Eloquent namely users, departments, and roles. A user can only have one department and one role. Here's how I've defined the models:
user model:
public function department(){
return $this->has_one('Department', 'department_id');
}
public function role(){
return $this->has_one('Role', 'role_id');
}
}
department
<?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');
}
}
role
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');
}
}
And here's how I'm accessing them in the controller:
$user = User::with(array('department', 'role'))->where('user_id', '=', 1)->first();
echo $user->department->department;
It's producing these queries:
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')
Any ideas?