thinkphp6.x出现的问题多对多模型关联belongsToMany的中间表pivot取不出数据
作者:互联网
public function role()
{
return $this->belongsToMany(Role::class, Access::class, 'role_id', 'auth_id');
}
这样取不到中间表数据
AuthModel::find(2)->role
解决
\vendor\topthink\think-orm\src\model\relation\BelongsToMany.php 中 getRelation 替换成旧版本的
/**
* 延迟获取关联数据
* @access public
* @param array $subRelation 子关联名
* @param Closure $closure 闭包查询条件
* @return Collection
*/
public function getRelation(array $subRelation = [], Closure $closure = null): Collection
{
if ($closure) {
$closure($this->getClosureType($closure));
}
$result = $this->buildQuery()
->relation($subRelation)
->select()
->setParent(clone $this->parent);
$this->hydratePivot($result);
return $result;
}
/**
* 创建关联查询Query对象
* @access protected
* @return Query
*/
protected function buildQuery(): Query
{
$foreignKey = $this->foreignKey;
$localKey = $this->localKey;
// 关联查询
$condition = ['pivot.' . $localKey, '=', $this->parent->getKey()];
return $this->belongsToManyQuery($foreignKey, $localKey, [$condition]);
}
拓展知识
laravel中可以通过在后面追加withPivot(['role_id','auth_id']) 来添加中间表字段
tp6默认取出中间表字段,可以通过 hiden(['pivot']) 隐藏整个中间表字段数据,或者隐藏指定字段
hiden(['pivot.role_id']);
参考地址:
https://blog.csdn.net/bluebird2/article/details/115106936
标签:closure,return,thinkphp6,role,pivot,belongsToMany,id,localKey 来源: https://www.cnblogs.com/lujiahao/p/15503979.html