通常来说,我们在写业务代码时候,会用到模型之间的关联,来代替join,提升查询性能,复杂一点的查询性能不太容易记住如何书写。
在Thinphp6框架中,记录一下经过中间表的多对多关系书写顺序
Apple表通过 M表(枢纽) 来查询到Type表
Apple表中的关联关系这么写
public function types()
{
return $this->hasManyThrough(
Type::class, // model 目标表
M::class, // through 枢纽表
'm.apple_id', // foreignKey 枢纽表对于本表的外键
'type.id',// throughKey目标表的对于枢纽表关联字段
'apple.id', // localKey本表对于枢纽表的关联字段
'm.type_id',// throughPk 枢纽表对于目标表的关联字段
);
}