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]);}