thinkphp6多对多模型关联belongsToMany的中间表pivot取不出数据
2022-11-24 11:10:29
186
{{single.collect_count}}
public function role(){return $this->belongsToMany(Role::class, Access::class, 'role_id', 'auth_id');}

 

测试版本:6.0.7

return AuthModel::find(2)->role;后取不到中间表数据,用6.0.3的vendor覆盖6.0.7后能正常显示,说明不是自己代码问题

[{"id":2,"type":"用户查询","url":"","pivot":[]}]

正确的

[{"id":2,"type":"用户查询","url":"","pivot":{"id":2,"auth_id":2,"role_id":2}}]

解决方法:

\vendor\topthink\think-orm\src\model\relation\BelongsToMany.php 中 getRelation 替换成旧版本的

 

 /** * 延迟获取关联数据 * @access public * @paramarray$subRelation 子关联名 * @paramClosure$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]);}

 

 

 

 

回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}