【问题标题】:Laravel Eloquent Join 2 TablesLaravel Eloquent 连接 2 个表
【发布时间】:2014-05-20 10:09:21
【问题描述】:

这些是我的模型:

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();

错误提示:

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

如何使用 Eloquent 实现这一目标?

【问题讨论】:

    标签: php join laravel-4 eloquent


    【解决方案1】:
    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 />';
    }
    

    【讨论】:

    • 谢谢,这是我的第一个解决方案,但我尝试使用连接,所以查询只有一行并最小化数据库连接
    • 您关于院系功能的第二个解决方案有效return $this-&gt;hasMany('Faculty', 'branch_name', 'name');。非常感谢:D
    • 是的,也可以加入字符串字段:),很高兴为您提供帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 2019-09-06
    • 1970-01-01
    • 2018-08-07
    • 2019-12-06
    • 2021-01-05
    • 2018-11-06
    相关资源
    最近更新 更多