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
