这些是我的模特:
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数据。
我想工作流程将是:
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实现这一目标?
答案 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 />';
}