php - Laravel 5.6 Eloquent Relations 2 级
解决方案
Keep the columns being named as what you wrote in the relation chart, and name the tables as years, depts, candidates, then define Year hasMany Dept, and hasMany Candidate:
class Year extends Model
{
public function depts()
{
return $this->hasMany('App\Dept');
}
public function candidates()
{
return $this->hasMany('App\Candidate');
}
}
Then you can take them all by with method, in Controller:
$years = App\Year::with(['depts', 'candidates'])->get();
UPDATE
Candidate can also be the main model by applying Nested Eager Loading.
make sure you've defined Candidate and Dept first:
Candidate Model
class Candidate extends Model
{
public function Year()
{
return $this->belongsTo('App\Year');
}
}
Dept Model
class Dept extends Model
{
public function Year()
{
return $this->belongsTo('App\Year');
}
}
In Controller
$candidates = App\Candidate::with('year.depts')->get();
推荐阅读
- django - 使用关键字参数 '{'id_operation': ''}' 反转 'operation_info'
- r - 使用R如何删除特定字符后的所有单词
- python - 在熊猫的不同列中查找相等的值
- c++ - 如何检测 << 运算符链的结尾
- python - 如何向 stevedore ExtensionManager 添加新的扩展
- c - 位平行加权 Levenshtein 距离
- skiasharp - DrawText 在 Windows 中工作,在 Linux 中为空(Synology armv7l)
- html - 通过 R 笔记本渲染 kable 对象时的白色字体
- python - Python、Django:原始 sql 查询的替代方案
- flutter - Flutter中如何实现多层循环ListView?