1. 程式人生 > 其它 >thinkphp6.x出現的問題多對多模型關聯belongsToMany的中間表pivot取不出資料

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