Laravel Eloquent加入2桌

时间:2014-05-20 10:09:22

标签: php join laravel-4 eloquent

这些是我的模特:

class Branch extends Eloquent {

    protected $table = 'tb_branch';

    public function faculty() 
    {
        return $this->hasMany('Faculty');
    }
}

class Faculty extends Eloquent {

    protected $table = 'tb_faculty';

    public function branch() 
    {
        return $this->belongsTo('Branch');
    }

}

在分支表中,我设置了一个链接到用户表的外键user_id的列。

在教师表中,我设置了一个包含外键branch的列,该列链接到具有列name的分支表。

现在我需要根据当前登录的用户(使用Eloquent)检索Faculty数据。

我想工作流程将是:

  • 检索当前登录用户的ID
  • 将该ID链接到分支的user_id并检索分支的name
  • 将该分支的name链接到教师分支name并检索所有匹配的教师数据

现在这是我尝试过的,但它不起作用:

$user_id = Sentry::getUser();
$faculty = Faculty::with('branch')->where('branch.user_id',$user->id)->get();

错误说:

  

'where子句'中的未知列'branch.user_id'(SQL:select * from   tb_faculty branchuser_id = 6)

如何通过Eloquent实现这一目标?

1 个答案:

答案 0 :(得分:3)

retrieve id of currently logged in user
link that id to the branch's user_id and retrieve branch's name
link that branch's name to faculty branch's name and retrieve all matched faculty data

所以,第一种方式:

$user_id = Auth::user()->id;
$branch = Branch::where('user_id', '=', $user_id)->first();
$faculties = Faculty::where('branch_name', '=', $branch->name)->get();
第二种方式:

如果院系是基于名称,那么:

class Branch extends Eloquent {

   public function faculties() {

    return Faculty::where('branch_name', '=', $this->name)->get();
    /*

     or do this: return $this->hasMany('Faculty', 'branch_name', 'name');       

    */

   }


}

然后这样做:

$user_id = Auth::user()->id;
$faculties = Branch::where('user_id', '=', $user_id)->first()->faculties;

然后在视图中:

foreach($faculties as $fac)
{

  echo $fac->name.'<br />';
}