改进多对多查询

This commit is contained in:
thinkphp
2016-11-30 17:11:38 +08:00
parent 6f58a26097
commit 61462a628e

View File

@@ -662,32 +662,36 @@ class Relation
public function __call($method, $args) public function __call($method, $args)
{ {
static $baseQuery = [];
if ($this->query) { if ($this->query) {
switch ($this->type) { if (empty($baseQuery[$this->type])) {
case self::HAS_MANY: $baseQuery[$this->type] = true;
if (isset($this->where)) { switch ($this->type) {
$this->query->where($this->where); case self::HAS_MANY:
} elseif (isset($this->parent->{$this->localKey})) { if (isset($this->where)) {
// 关联查询带入关联条件 $this->query->where($this->where);
$this->query->where($this->foreignKey, $this->parent->{$this->localKey}); } elseif (isset($this->parent->{$this->localKey})) {
} // 关联查询带入关联条件
break; $this->query->where($this->foreignKey, $this->parent->{$this->localKey});
case self::HAS_MANY_THROUGH: }
$through = $this->middle; break;
$model = $this->model; case self::HAS_MANY_THROUGH:
$alias = Loader::parseName(basename(str_replace('\\', '/', $model))); $through = $this->middle;
$throughTable = $through::getTable(); $model = $this->model;
$pk = (new $this->model)->getPk(); $alias = Loader::parseName(basename(str_replace('\\', '/', $model)));
$throughKey = $this->throughKey; $throughTable = $through::getTable();
$modelTable = $this->parent->getTable(); $pk = (new $this->model)->getPk();
$this->query->field($alias . '.*')->alias($alias) $throughKey = $this->throughKey;
->join($throughTable, $throughTable . '.' . $pk . '=' . $alias . '.' . $throughKey) $modelTable = $this->parent->getTable();
->join($modelTable, $modelTable . '.' . $this->localKey . '=' . $throughTable . '.' . $this->foreignKey) $this->query->field($alias . '.*')->alias($alias)
->where($throughTable . '.' . $this->foreignKey, $this->parent->{$this->localKey}); ->join($throughTable, $throughTable . '.' . $pk . '=' . $alias . '.' . $throughKey)
break; ->join($modelTable, $modelTable . '.' . $this->localKey . '=' . $throughTable . '.' . $this->foreignKey)
case self::BELONGS_TO_MANY: ->where($throughTable . '.' . $this->foreignKey, $this->parent->{$this->localKey});
// TODO break;
case self::BELONGS_TO_MANY:
$pk = $this->parent->getPk();
$this->query->join($this->middle . ' pivot', 'pivot.' . $this->foreignKey . '=' . $this->query->getTable() . '.' . $this->query->getPk())->where('pivot.' . $this->localKey, $this->parent->$pk);
}
} }
$result = call_user_func_array([$this->query, $method], $args); $result = call_user_func_array([$this->query, $method], $args);
if ($result instanceof \think\db\Query) { if ($result instanceof \think\db\Query) {