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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM