eloquent 多 table 查询和关系
eloquent multi table query and relationships
我是新手,请多多包涵。
我有 4 个 table(用户、分数、记分卡、课程),我需要从所有这些 table 中获取视图信息。
关系如下:
评分模型
public function user(){
return $this->belongsTo('App\User');
}
public function scorecard(){
return $this->belongsTo('App\Scorecard');
}
public function course() {
return $this->belongsTo('App\Course');
}
课程模型
public function club(){
return $this->belongsTo('App\Club');
}
public function scorecard(){
return $this->hasMany('App\Scorecard');
}
public function score() {
return $this->hasMany('App\Score');
}
记分卡模型
public function course(){
return $this->belongsTo('App\Course');
}
public function club(){
return $this->belongsTo('App\Club');
}
在我的控制器中,我从请求的下拉列表中获取分数 ID。我基本上需要获取以下信息:
- 分数记录,有分数id就很简单
- use the scorecard_id from the scores table 从scorecards中获取scorecard记录 table
- 使用记分卡 table 中的 course_id 从课程 table 中获取课程信息 table。
如果 $id
是下拉列表中的分数 ID,
$score=Score::with('scorecard','scorecard.course')->where(['id'=$id])->first();
然后,
print_r($score);
给出分数记录。
print_r($score->scorecard);
给出记分卡记录。
print_r($score->scorecard->course);
给出课程记录。
您可以使用点 .
作为 scorecard.course
预先加载关系,它会同时加载记分卡和课程。
$score = Score::with('scorecard.course')->find($id);
然后您可以访问相应的属性:
$score->scorecard;
$score->scorecard->course;
我是新手,请多多包涵。
我有 4 个 table(用户、分数、记分卡、课程),我需要从所有这些 table 中获取视图信息。
关系如下:
评分模型
public function user(){
return $this->belongsTo('App\User');
}
public function scorecard(){
return $this->belongsTo('App\Scorecard');
}
public function course() {
return $this->belongsTo('App\Course');
}
课程模型
public function club(){
return $this->belongsTo('App\Club');
}
public function scorecard(){
return $this->hasMany('App\Scorecard');
}
public function score() {
return $this->hasMany('App\Score');
}
记分卡模型
public function course(){
return $this->belongsTo('App\Course');
}
public function club(){
return $this->belongsTo('App\Club');
}
在我的控制器中,我从请求的下拉列表中获取分数 ID。我基本上需要获取以下信息:
- 分数记录,有分数id就很简单
- use the scorecard_id from the scores table 从scorecards中获取scorecard记录 table
- 使用记分卡 table 中的 course_id 从课程 table 中获取课程信息 table。
如果 $id
是下拉列表中的分数 ID,
$score=Score::with('scorecard','scorecard.course')->where(['id'=$id])->first();
然后,
print_r($score);
给出分数记录。
print_r($score->scorecard);
给出记分卡记录。
print_r($score->scorecard->course);
给出课程记录。
您可以使用点 .
作为 scorecard.course
预先加载关系,它会同时加载记分卡和课程。
$score = Score::with('scorecard.course')->find($id);
然后您可以访问相应的属性:
$score->scorecard;
$score->scorecard->course;