laravel hasManyThrough用法及参数(转)

原文:https://learnku.com/articles/62503

简单模式

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

copycountries
    id - integer
    name - string

users
    id - integer
    country_id - integer
    name - string

posts
    id - integer
    user_id - integer
    title - string

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

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

纯中间表

第二种情况,有中间表情况

copyexam_paper(试卷表):id,name

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

exam_question(试题表):id,name

我们要通过 exam_paper 的 id 查询 question

copyreturn $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)

posted @   pine007  阅读(500)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构

目录导航

点击右上角即可分享
微信分享提示