改进远程一对多查询

This commit is contained in:
thinkphp
2016-05-25 18:17:45 +08:00
parent e890d43d55
commit 15de3e328a
2 changed files with 29 additions and 18 deletions

View File

@@ -740,10 +740,16 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
$model = new static();
$info = $model->$relation()->getRelationInfo();
$table = $info['model']::getTable();
return $model->db()->alias('a')
->join($table . ' b', 'a.' . $info['localKey'] . '=b.' . $info['foreignKey'])
->group('b.' . $info['foreignKey'])
->having('count(' . $id . ')' . $operator . $count);
switch($info['type']){
case Relation::HAS_MANY:
return $model->db()->alias('a')
->join($table . ' b', 'a.' . $info['localKey'] . '=b.' . $info['foreignKey'])
->group('b.' . $info['foreignKey'])
->having('count(' . $id . ')' . $operator . $count);
case Relation::HAS_MANY_THROUGH:
// TODO
}
}
/**
@@ -757,19 +763,24 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
{
$model = new static();
$info = $model->$relation()->getRelationInfo();
$table = $info['model']::getTable();
if (is_array($where)) {
foreach ($where as $key => $val) {
if (false === strpos($key, '.')) {
$where['b.' . $key] = $val;
unset($where[$key]);
switch($info['type']){
case Relation::HAS_MANY:
$table = $info['model']::getTable();
if (is_array($where)) {
foreach ($where as $key => $val) {
if (false === strpos($key, '.')) {
$where['b.' . $key] = $val;
unset($where[$key]);
}
}
}
}
return $model->db()->alias('a')
->field('a.*')
->join($table . ' b', 'a.' . $info['localKey'] . '=b.' . $info['foreignKey'])
->where($where);
case Relation::HAS_MANY_THROUGH:
// TODO
}
return $model->db()->alias('a')
->field('a.*')
->join($table . ' b', 'a.' . $info['localKey'] . '=b.' . $info['foreignKey'])
->where($where);
}
/**

View File

@@ -664,13 +664,13 @@ class Relation
case self::HAS_MANY_THROUGH:
$through = $this->middle;
$model = $this->model;
$table = $model::getTable();
$alias = Loader::parseName(basename(str_replace('\\', '/', $model)));
$throughTable = $through::getTable();
$pk = (new $this->model)->getPk();
$throughKey = $this->throughKey;
$modelTable = $this->parent->getTable();
$result = $db->field($table.'.*')
->join($throughTable,$throughTable.'.'.$pk.'='.$table.'.'.$throughKey)
$result = $db->field($alias.'.*')->alias($alias)
->join($throughTable,$throughTable.'.'.$pk.'='.$alias.'.'.$throughKey)
->join($modelTable,$modelTable.'.'.$this->localKey.'='.$throughTable.'.'.$this->foreignKey)
->where($throughTable.'.'.$this->foreignKey, $this->parent->{$this->localKey});
break;