-
/**
-
* HAS ONE 远程关联定义
-
* @access public
-
* @param string $model 模型名
-
* @param string $through 中间模型名
-
* @param string $foreignKey 关联外键
-
* @param string $throughKey 关联外键
-
* @param string $localKey 当前主键
-
* @param string $throughPk 中间表主键
-
* @return HasOneThrough
-
*/
-
public
function hasOneThrough(string $model, string $through, string $foreignKey = '', string $throughKey = '', string $localKey = '', string $throughPk = ''): HasOneThrough
-
{
-
// 记录当前关联信息
-
$model =
$this->parseModel($model);
-
$through =
$this->parseModel($through);
-
$localKey = $localKey ?:
$this->getPk();
-
$foreignKey = $foreignKey ?:
$this->getForeignKey(
$this->name);
-
$throughKey = $throughKey ?:
$this->getForeignKey((
new $through)->getName());
-
$throughPk = $throughPk ?: (
new $through)->getPk();
-
-
return
new HasOneThrough(
$this, $model, $through, $foreignKey, $throughKey, $localKey, $throughPk);
-
}
源码长这样,但是参数注释中的模型名,中间模型,关联外键等一系列名词不容易理解到底该填什么,默认的外键和关联外键命名规则是 当前模型名+_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的参数写法应该如下
-
public
function assessCompany(){
-
/* 用白话文讲6个参数意思,注意参数3,5配对 参数4,6配对
-
* 参数1,我最终需要获取的那张表的模型
-
* 参数2,我需要使用到的中间表模型
-
* 参数3,中间表与主表相等的字段 (本例为id=assess_effect_id)
-
* 参数4,目标表与中间表相等的字段 (本例为company_id=id)
-
* 参数5,主表与中间表相等的字段 (本例为id=assess_effect_id)
-
* 参数6,中间表与目标表相等的字段 (本例为company_id=id)
-
* */
-
return
$this->hasOneThrough(CompanyInfo::class,AssessEffect::class,
'表2.id',
'表3.id',
'表1.assess_effect_id',
'表2.company_id');
-
}
不知道这样解释是否能更明白一些,如果能帮助到其他人是我莫大的荣幸。如果有帮到你,就帮我点个赞吧
转载:https://blog.csdn.net/qq449736038/article/details/117281632
查看评论