php Laravel Eloquent 连接 2 个表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23756858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Eloquent Join 2 Tables
提问by user2002495
These are my models:
这些是我的模型:
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');
}
}
In branch table I have set a column with foreign key user_id
that links to users table.
在分支表中,我设置了一个带有user_id
链接到用户表的外键的列。
In faculty table I have set a column with foreign key branch
which links to branch table with column name
.
在教师表中,我设置了一个带有外键的列,该列branch
链接到带有列的分支表name
。
And now I need to retrieve Faculty data based on currently logged in user (with Eloquent).
现在我需要根据当前登录的用户(使用 Eloquent)检索 Faculty 数据。
I imagine the work flow would be:
我想工作流程是:
- retrieve id of currently logged in user
- link that id to the branch's
user_id
and retrieve branch'sname
- link that branch's
name
to faculty branch'sname
and retrieve all matched faculty data
- 检索当前登录用户的 id
- 将该 id 链接到分支的
user_id
并检索分支的name
- 将该分支链接
name
到教师分支name
并检索所有匹配的教师数据
Now this is what I have tried, it didn't work:
现在这是我尝试过的,但没有奏效:
$user_id = Sentry::getUser();
$faculty = Faculty::with('branch')->where('branch.user_id',$user->id)->get();
Error says:
错误说:
Unknown column 'branch.user_id' in 'where clause' (SQL: select * from
tb_faculty
wherebranch
.user_id
= 6)
“where 子句”中的未知列“branch.user_id”(SQL:select * from
tb_faculty
wherebranch
.user_id
= 6)
How can I achieve this with Eloquent?
我如何使用 Eloquent 实现这一目标?
回答by Rustam
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
so, first way:
所以,第一种方式:
$user_id = Auth::user()->id;
$branch = Branch::where('user_id', '=', $user_id)->first();
$faculties = Faculty::where('branch_name', '=', $branch->name)->get();
second way:
第二种方式:
if faculties are based on name, then:
如果院系基于名称,则:
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');
*/
}
}
Then do this:
然后这样做:
$user_id = Auth::user()->id;
$faculties = Branch::where('user_id', '=', $user_id)->first()->faculties;
then in the view:
然后在视图中:
foreach($faculties as $fac)
{
echo $fac->name.'<br />';
}