laravel hasManyThrough用法及参数

第一种情况,我称之为传导关联表(简单模式)
国家有很多用户,用户有很多帖子

countries
    id - integer
    name - string

users
    id - integer
    country_id - integer
    name - string

posts
    id - integer
    user_id - integer
    title - string

查询某个国家的所有帖子,怎么实现?
countries为本表,posts为要输出的目标表,users为中间表

return $this->hasManyThrough('App\Post', 'App\User', 'country_id', 'user_id');

第二种情况,有中间表情况(纯中间表)

exam_paper(试卷表)
id
name

exam_paper_question(试卷与试题中间表)
id
exam_paper_id
question_id

exam_question(试题表)
id
name

我们要通过exam_paper的id查询question

return $this->hasManyThrough('exam_question', 'exam_paper_question', 'exam_paper_id', 'id''id''question_id');
// 参数1 目标表类名
exam_question,
// 参数2 枢纽表类名
exam_paper_question,
// 参数3 枢纽表中和当前表关联的字段名
'exam_paper_question.exam_paper_id',
// 参数4 目标表和枢纽表关联的字段名
'exam_question.id',
// 参数5 当前表中和枢纽表关联的字段名
'exam_paper.id',
// 参数6 枢纽表和目标表关联的字段名
'exam_paper_question.question_id');

如果把当前表记作A,目标表记作B,中间表记作C,6个参数记作(B,C,CA,BC,AC,CB)

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 2

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!