Tp5多对多关联注意事项

让人想犯罪 __ 提交于 2020-04-18 17:34:03

用多对多关联的时候,因为执行baseQuery之后就会锁定id,导致relation只有第一个成功. 两个解决思路

  1. 其它关联方式,嵌套关联
  2. 自己构建belongsToMany类,覆盖model的belongsToMany方法

Relation.php

    public function __call($method, $args)
    {
        if ($this->query) {
            // 执行基础查询
            $this->baseQuery();

            $result = call_user_func_array([$this->query->getModel(), $method], $args);

            return $result === $this->query && !in_array(strtolower($method), ['fetchsql', 'fetchpdo']) ? $this : $result;
        } else {
            throw new Exception('method not exists:' . __CLASS__ . '->' . $method);
        }
    }

BelongsToMany.php

    /**
     * 执行基础查询(仅执行一次)
     * @access protected
     * @return void
     */
    protected function baseQuery()
    {
        if (empty($this->baseQuery) && $this->parent->getData()) {
            $pk    = $this->parent->getPk();
            $table = $this->pivot->getTable();

            $this->query
                ->join([$table => 'pivot'], 'pivot.' . $this->foreignKey . '=' . $this->query->getTable() . '.' . $this->query->getPk())
                ->where('pivot.' . $this->localKey, $this->parent->$pk);
            $this->baseQuery = true;
        }
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!