Laravel - 在Eloquent中加入3张桌子

时间:2012-11-26 12:07:01

标签: php laravel laravel-3

我正在尝试加入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')

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

我相信你混淆了关系方法, 来自laravel docs

class User extends Eloquent {

 public function phone()
 {
      return $this->has_one('Phone', 'my_foreign_key');
 }
}

标识符 my_foreign_key 是电话表中外键的名称,它引用用户ID(关系的所有者)。所以在你的情况下

public function department(){
    return $this->has_one('Department', 'your_user_id');
}

其中 your_user_id 是您在deparments表中用来引用其所属用户的字段。以及你提供的其他例子

目前您正在设置外键以引用同一个表而不是其所有者。

相关问题