小言_互联网的博客

【PHP】thinkphp6远程一对一hansOneThrough使用,白话文参数解释

371人阅读  评论(0)

  
  1. /**
  2. * HAS ONE 远程关联定义
  3. * @access public
  4. * @param string $model 模型名
  5. * @param string $through 中间模型名
  6. * @param string $foreignKey 关联外键
  7. * @param string $throughKey 关联外键
  8. * @param string $localKey 当前主键
  9. * @param string $throughPk 中间表主键
  10. * @return HasOneThrough
  11. */
  12. public function hasOneThrough(string $model, string $through, string $foreignKey = '', string $throughKey = '', string $localKey = '', string $throughPk = ''): HasOneThrough
  13. {
  14. // 记录当前关联信息
  15. $model = $this->parseModel($model);
  16. $through = $this->parseModel($through);
  17. $localKey = $localKey ?: $this->getPk();
  18. $foreignKey = $foreignKey ?: $this->getForeignKey( $this->name);
  19. $throughKey = $throughKey ?: $this->getForeignKey(( new $through)->getName());
  20. $throughPk = $throughPk ?: ( new $through)->getPk();
  21. return new HasOneThrough( $this, $model, $through, $foreignKey, $throughKey, $localKey, $throughPk);
  22. }

源码长这样,但是参数注释中的模型名,中间模型,关联外键等一系列名词不容易理解到底该填什么,默认的外键和关联外键命名规则是 当前模型名+_id,实际项目中关联键的名称可能并没有这么理想。笔者做了无数次远程一对一/远程一对多之后仍然记不住这几个参数的意思,终于决定使用文章记录下来,方便自己也方便他人使用。

先看使用场景

表assess_effect_advisor  表1

表assess_effect  表2

表company_info  表3

表1为主表,希望通过表2,查出表3的数据

主要关系字段已用红圈标注出来了,3张表的关系是,表1字段assess_effect_id关联表2 id, 表2 compnay_id关联 表3 id

hasOneThrough的参数写法应该如下


  
  1. public function assessCompany(){
  2. /* 用白话文讲6个参数意思,注意参数3,5配对 参数4,6配对
  3. * 参数1,我最终需要获取的那张表的模型
  4. * 参数2,我需要使用到的中间表模型
  5. * 参数3,中间表与主表相等的字段 (本例为id=assess_effect_id)
  6. * 参数4,目标表与中间表相等的字段 (本例为company_id=id)
  7. * 参数5,主表与中间表相等的字段 (本例为id=assess_effect_id)
  8. * 参数6,中间表与目标表相等的字段 (本例为company_id=id)
  9. * */
  10. return $this->hasOneThrough(CompanyInfo::class,AssessEffect::class, '表2.id', '表3.id', '表1.assess_effect_id', '表2.company_id');
  11. }

不知道这样解释是否能更明白一些,如果能帮助到其他人是我莫大的荣幸。如果有帮到你,就帮我点个赞吧


转载:https://blog.csdn.net/qq449736038/article/details/117281632
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场