Php Laravel雄辩地连接2个表

Php Laravel雄辩地连接2个表,php,join,laravel-4,eloquent,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'; publ

这些是我的模型:

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\u id的列,该列链接到users表

在faculty表中,我设置了一个带有外键
branch
的列,该列链接到带有column
name
的branch表

现在我需要根据当前登录的用户检索教员数据(带有Eloquent)

我想工作流程是:

  • 检索当前登录用户的id
  • 将该id链接到分支机构的
    用户id
    并检索分支机构的
    名称
  • 将该分支机构的
    名称
    链接到教员分支机构的
    名称
    ,并检索所有匹配的教员数据
这是我尝试过的,但没有成功:

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

“where子句”(SQL:select*from)中的未知列“branch.user_id”
tbu教员
其中
分支机构
用户id
=6)

我怎样才能做到这一点与雄辩

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 />';
}
foreach($faculties作为$fac)
{
echo$fac->name.“
”; }
谢谢,这是我的第一个解决方案,但我尝试使用join,因此查询只需一行,并最小化数据库连接。faculties函数的第二个解决方案有效
return$this->hasMany('Faculty'、'branch_name'、'name')。非常感谢:您还可以加入以下字段:),很高兴为您提供帮助