繁体   English   中英

Laravel雄辩地加入2张桌子

[英]Laravel Eloquent Join 2 Tables

这些是我的模型:

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)来检索学院数据。

我想工作流程将是:

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

现在这是我尝试过的方法,但是没有用:

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

错误提示:

未知列在'branch.user_id' 'where子句'(SQL:SELECT * FROM tb_faculty其中branchuser_id = 6)

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

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 />';
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM