From d8ac3574f5614ad8f31a5d56a210a793e6a637a8 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sun, 17 Apr 2016 13:03:47 +0800 Subject: [PATCH] =?UTF-8?q?=E5=85=B3=E8=81=94=E6=A8=A1=E5=9E=8B=E6=8B=86?= =?UTF-8?q?=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Model.php | 263 +++-------------------- library/think/db/Query.php | 14 +- library/think/model/Relation.php | 344 +++++++++++++++++++++++++++++++ 3 files changed, 385 insertions(+), 236 deletions(-) create mode 100644 library/think/model/Relation.php diff --git a/library/think/Model.php b/library/think/Model.php index d945b3bb..16fe48be 100644 --- a/library/think/Model.php +++ b/library/think/Model.php @@ -15,13 +15,10 @@ use think\Cache; use think\Db; use think\db\Query; use think\Loader; +use think\model\Relation; abstract class Model implements \JsonSerializable, \ArrayAccess { - const HAS_ONE = 1; - const HAS_MANY = 2; - const BELONGS_TO = 3; - const BELONGS_TO_MANY = 4; // 当前实例 private static $instance; @@ -65,10 +62,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess protected $type = []; // 是否为更新数据 protected $isUpdate = false; - // 当前执行的关联信息 - private $relation; - // 是否预载入 - protected $eagerly = false; + // 当前执行的关联对象 + protected $relation; /** * 初始化过的模型. @@ -92,6 +87,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $this->name = basename(str_replace('\\', '/', get_class($this))); $this->initialize(); + $this->relation = new Relation($this); } /** @@ -264,38 +260,13 @@ abstract class Model implements \JsonSerializable, \ArrayAccess } } elseif (is_null($value) && method_exists($this, $name)) { // 获取关联数据 - return $this->getRelation($name); + $value = $this->relation->getRelation($name); + // 保存关联对象值 + $this->data[$name] = $value; } return $value; } - // 获取关联数据 - protected function getRelation($relation) - { - // 执行关联定义方法 - $db = $this->$relation(); - // 判断关联类型执行查询 - switch ($this->relation[0]) { - case self::HAS_ONE: - case self::BELONGS_TO: - $result = $db->find(); - break; - case self::HAS_MANY: - case self::BELONGS_TO_MANY: - $result = $db->select(); - break; - default: - // 直接返回 - $result = $db; - } - // 避免影响其它操作方法 - $this->relation = []; - // 保存关联对象值 - $this->data[$relation] = $result; - - return $result; - } - /** * 检测数据对象的值 * @access public @@ -736,14 +707,20 @@ abstract class Model implements \JsonSerializable, \ArrayAccess $relations = explode(',', $relations); } foreach ($relations as $relation) { - $this->data[$relation] = $this->getRelation($relation); + $this->data[$relation] = $this->relation->getRelation($relation); } return $this; } - public function getRelationInfo() + /** + * 获取当前关联信息 + * @access public + * @param string $name 关联信息 + * @return array|string|integer + */ + public function getRelationInfo($name = '') { - return $this->relation; + return $this->relation->getRelationInfo($name); } /** @@ -755,55 +732,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public function eagerlyResultSet($resultSet, $relation) { - $this->eagerly = true; - $relations = is_string($relation) ? explode(',', $relation) : $relation; - - foreach ($relations as $relation) { - $subRelation = ''; - if (strpos($relation, '.')) { - list($relation, $subRelation) = explode('.', $relation); - } - // 执行关联方法 - $model = $this->$relation(); - // 获取关联信息 - list($type, $foreignKey, $localKey) = $this->relation; - - switch ($type) { - case self::HAS_ONE: - case self::BELONGS_TO: - foreach ($resultSet as $result) { - // 模型关联组装 - $this->modelRelationBuild($model, $relation, $result); - } - break; - case self::HAS_MANY: - case self::BELONGS_TO_MANY: - $range = []; - foreach ($resultSet as $result) { - // 获取关联外键列表 - if (isset($result->$localKey)) { - $range[] = $result->$localKey; - } - } - - if (!empty($range)) { - $data = $this->modelRelationQuery($model, [$foreignKey => ['in', $range]], $relation, $subRelation); - - // 关联数据封装 - foreach ($resultSet as $result) { - if (isset($data[$result->$localKey])) { - $result->__set($relation, $data[$result->$localKey]); - } else { - $result->__set($relation, []); - } - } - } - break; - } - $this->relation = []; - } - $this->eagerly = false; - return $resultSet; + return $this->relation->eagerlyResultSet($resultSet, $relation); } /** @@ -815,103 +744,8 @@ abstract class Model implements \JsonSerializable, \ArrayAccess */ public function eagerlyResult($result, $relation) { - $this->eagerly = true; - $relations = is_string($relation) ? explode(',', $relation) : $relation; + return $this->relation->eagerlyResult($result, $relation); - foreach ($relations as $relation) { - $subRelation = ''; - if (strpos($relation, '.')) { - list($relation, $subRelation) = explode('.', $relation); - } - // 执行关联方法 - $model = $this->$relation(); - // 获取关联信息 - list($type, $foreignKey, $localKey) = $this->relation; - - switch ($type) { - case self::HAS_ONE: - case self::BELONGS_TO: - // 模型关联组装 - $this->modelRelationBuild($model, $relation, $result); - break; - case self::HAS_MANY: - case self::BELONGS_TO_MANY: - if (isset($result->$localKey)) { - $data = $this->modelRelationQuery($model, [$foreignKey => $result->$localKey], $relation, $subRelation); - // 关联数据封装 - if (!isset($data[$result->$localKey])) { - $data[$result->$localKey] = []; - } - $result->__set($relation, $data[$result->$localKey]); - } - break; - } - $this->relation = []; - } - $this->eagerly = false; - - return $result; - } - - /** - * 一对一 关联模型预查询拼装 - * @access public - * @param string $model 模型名称 - * @param string $relation 关联名 - * @param Model $result 模型对象实例 - * @return void - */ - protected function modelRelationBuild($model, $relation, &$result) - { - $modelName = strtolower(basename(str_replace('\\', '/', $model))); - $currName = strtolower($this->name); - // 重新组装模型数据 - foreach ($result->toArray() as $key => $val) { - if (strpos($key, '__')) { - list($name, $attr) = explode('__', $key); - if (in_array($name, [$currName, $modelName])) { - $list[$name][$attr] = $val; - unset($result->$key); - } - } - } - - // 当前模型属性设置 - if (isset($list[$currName])) { - foreach ($list[$currName] as $name => $val) { - $result->__set($name, $val); - } - } - - if (!isset($list[$modelName])) { - // 设置关联模型属性 - $list[$modelName] = []; - } - $result->__set($relation, new $model($list[$modelName])); - } - - /** - * 一对多 关联模型预查询 - * @access public - * @param string $model 模型名称 - * @param array $where 关联预查询条件 - * @param string $relation 关联名 - * @param string $subRelation 子关联 - * @return void - */ - protected function modelRelationQuery($model, $where, $relation, $subRelation = '') - { - list($type, $foreignKey, $localKey) = $this->relation; - - // 预载入关联查询 支持嵌套预载入 - $list = $model::where($where)->with($subRelation)->select(); - - // 组装模型数据 - $data = []; - foreach ($list as $set) { - $data[$set->$foreignKey][] = $set; - } - return $data; } /** @@ -925,18 +759,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess public function hasOne($model, $foreignKey = '', $localKey = '') { // 记录当前关联信息 - $localKey = $localKey ?: $this->pk; - $foreignKey = $foreignKey ?: Loader::parseName($this->name) . '_id'; - $this->relation = [self::HAS_ONE, $foreignKey, $localKey]; - - $model = $this->parseModel($model); - if (!$this->eagerly && isset($this->data[$localKey])) { - // 关联查询封装 - return $model::where($foreignKey, $this->data[$localKey]); - } else { - // 预载入封装 - return $model; - } + $model = $this->parseModel($model); + $localKey = $localKey ?: $this->pk; + $foreignKey = $foreignKey ?: Loader::parseName($this->name) . '_id'; + return $this->relation->hasOne($model, $foreignKey, $localKey); } /** @@ -950,17 +776,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess public function belongsTo($model, $localKey = '', $foreignKey = '') { // 记录当前关联信息 - $foreignKey = $foreignKey ?: $this->pk; - $localKey = $localKey ?: Loader::parseName(basename(str_replace('\\', '/', $model))) . '_id'; - $this->relation = [self::BELONGS_TO, $foreignKey, $localKey]; - - $model = $this->parseModel($model); - if (!$this->eagerly && isset($this->data[$localKey])) { - // 关联查询封装 - return $model::where($foreignKey, $this->data[$localKey]); - } else { - return $model; - } + $model = $this->parseModel($model); + $foreignKey = $foreignKey ?: $this->pk; + $localKey = $localKey ?: Loader::parseName(basename(str_replace('\\', '/', $model))) . '_id'; + return $this->relation->belongsTo($model, $foreignKey, $localKey); } /** @@ -974,17 +793,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess public function hasMany($model, $foreignKey = '', $localKey = '') { // 记录当前关联信息 - $localKey = $localKey ?: $this->pk; - $foreignKey = $foreignKey ?: Loader::parseName($this->name) . '_id'; - $this->relation = [self::HAS_MANY, $foreignKey, $localKey]; - - $model = $this->parseModel($model); - if (!$this->eagerly && isset($this->data[$localKey])) { - // 关联查询封装 - return $model::where($foreignKey, $this->data[$localKey]); - } else { - return $model; - } + $model = $this->parseModel($model); + $localKey = $localKey ?: $this->pk; + $foreignKey = $foreignKey ?: Loader::parseName($this->name) . '_id'; + return $this->relation->hasMany($model, $foreignKey, $localKey); } /** @@ -998,17 +810,10 @@ abstract class Model implements \JsonSerializable, \ArrayAccess public function belongsToMany($model, $localKey = '', $foreignKey = '') { // 记录当前关联信息 - $foreignKey = $foreignKey ?: $this->pk; - $localKey = $localKey ?: Loader::parseName(basename(str_replace('\\', '/', $model))) . '_id'; - $this->relation = [self::BELONGS_TO_MANY, $foreignKey, $localKey]; - - $model = $this->parseModel($model); - if (!$this->eagerly && isset($this->data[$localKey])) { - // 关联查询封装 - return $model::where($foreignKey, $this->data[$localKey]); - } else { - return $model; - } + $model = $this->parseModel($model); + $foreignKey = $foreignKey ?: $this->pk; + $localKey = $localKey ?: Loader::parseName(basename(str_replace('\\', '/', $model))) . '_id'; + return $this->relation->belongsToMany($model, $foreignKey, $localKey); } /** diff --git a/library/think/db/Query.php b/library/think/db/Query.php index 80d7b4c3..80a491ca 100644 --- a/library/think/db/Query.php +++ b/library/think/db/Query.php @@ -17,6 +17,7 @@ use think\Db; use think\Exception; use think\Loader; use think\Model; +use think\model\Relation; class Query { @@ -363,7 +364,7 @@ class Query * @param string $prefix 字段前缀 * @return $this */ - public function field($field, $except = false, $tableName = '', $prefix = '') + public function field($field, $except = false, $tableName = '', $prefix = '', $alias = '') { if (is_string($field)) { $field = explode(',', $field); @@ -382,7 +383,7 @@ class Query $prefix = $prefix ?: $tableName; foreach ($field as $key => $val) { if (is_numeric($key)) { - $val = $prefix . '.' . $val . ' AS ' . $prefix . '__' . $val; + $val = $prefix . '.' . $val . ($alias ? ' AS ' . $alias . $val : ''); } $field[$key] = $val; } @@ -832,20 +833,19 @@ class Query list($relation, $subRelation) = explode('.', $relation, 2); } - $model = $class->$relation(); - list($type, $foreignKey, $localKey) = $class->getRelationInfo(); - if (in_array($type, [Model::HAS_ONE, Model::BELONGS_TO])) { + $model = $class->$relation(); + $info = $class->getRelationInfo(); + if (in_array($info['type'], [Relation::HAS_ONE, Relation::BELONGS_TO])) { if (0 == $i) { $joinName = strtolower(basename(str_replace('\\', '/', $this->options['model']))); $joinTable = $this->connection->getTableName(); $this->table($joinTable)->alias($joinName)->field(true, false, $joinTable, $joinName); } // 预载入封装 - $table = $model::getTableName(); $name = strtolower(basename(str_replace('\\', '/', $model))); $this->via($name); - $this->join($table . ' ' . $name, $joinName . '.' . $localKey . '=' . $name . '.' . $foreignKey)->field(true, false, $table, $name); + $this->join($table . ' ' . $name, $joinName . '.' . $info['localKey'] . '=' . $name . '.' . $info['foreignKey'])->field(true, false, $table, $name, $name . '__'); if ($closure) { // 执行闭包查询 call_user_func_array($closure, [ & $this]); diff --git a/library/think/model/Relation.php b/library/think/model/Relation.php new file mode 100644 index 00000000..4402b3a6 --- /dev/null +++ b/library/think/model/Relation.php @@ -0,0 +1,344 @@ + +// +---------------------------------------------------------------------- + +namespace think\model; + +use think\Db; + +class Relation +{ + const HAS_ONE = 1; + const HAS_MANY = 2; + const BELONGS_TO = 3; + const BELONGS_TO_MANY = 4; + + // 父模型 + protected $parent; + // 当前的模型类 + protected $model; + // 中间表模型 + protected $middle; + // 当前关联类型 + protected $type; + // 关联外键 + protected $foreignKey; + // 关联键 + protected $localKey; + // 是否预载入 + protected $eagerly = false; + + /** + * 架构函数 + * @access public + * @param \think\Model $model 上级模型对象 + */ + public function __construct($model) + { + $this->parent = $model; + } + + /** + * 获取当前关联信息 + * @access public + * @param string $name 关联信息 + * @return array|string|integer + */ + public function getRelationInfo($name = '') + { + $info = [ + 'type' => $this->type, + 'model' => $this->model, + 'middle' => $this->middle, + 'foreignKey' => $this->foreignKey, + 'localKey' => $this->localKey, + ]; + return $name ? $info[$name] : $info; + } + + // 获取关联数据 + public function getRelation($relation) + { + // 执行关联定义方法 + $db = $this->parent->$relation(); + dump($this->type); + // 判断关联类型执行查询 + switch ($this->type) { + case self::HAS_ONE: + case self::BELONGS_TO:echo 'one'; + $result = $db->find(); + break; + case self::HAS_MANY: + case self::BELONGS_TO_MANY: + $result = $db->select(); + break; + default: + // 直接返回 + $result = $db; + } + return $result; + } + + /** + * 预载入关联查询 返回数据集 + * @access public + * @param array $resultSet 数据集 + * @param string $relation 关联名 + * @return array + */ + public function eagerlyResultSet($resultSet, $relation) + { + $this->eagerly = true; + $relations = is_string($relation) ? explode(',', $relation) : $relation; + + foreach ($relations as $relation) { + $subRelation = ''; + if (strpos($relation, '.')) { + list($relation, $subRelation) = explode('.', $relation); + } + // 执行关联方法 + $model = $this->parent->$relation(); + // 获取关联信息 + $localKey = $this->localKey; + $foreignKey = $this->foreignKey; + switch ($this->type) { + case self::HAS_ONE: + case self::BELONGS_TO: + foreach ($resultSet as $result) { + // 模型关联组装 + $this->modelRelationBuild($model, $relation, $result); + } + break; + case self::HAS_MANY: + case self::BELONGS_TO_MANY: + $range = []; + foreach ($resultSet as $result) { + // 获取关联外键列表 + if (isset($result->$localKey)) { + $range[] = $result->$localKey; + } + } + + if (!empty($range)) { + $data = $this->modelRelationQuery($model, [$foreignKey => ['in', $range]], $relation, $subRelation); + + // 关联数据封装 + foreach ($resultSet as $result) { + if (isset($data[$result->$localKey])) { + $result->__set($relation, $data[$result->$localKey]); + } else { + $result->__set($relation, []); + } + } + } + break; + } + $this->relation = []; + } + $this->eagerly = false; + return $resultSet; + } + + /** + * 预载入关联查询 返回模型对象 + * @access public + * @param Model $result 数据对象 + * @param string $relation 关联名 + * @return \think\Model + */ + public function eagerlyResult($result, $relation) + { + $this->eagerly = true; + $relations = is_string($relation) ? explode(',', $relation) : $relation; + + foreach ($relations as $relation) { + $subRelation = ''; + if (strpos($relation, '.')) { + list($relation, $subRelation) = explode('.', $relation); + } + // 执行关联方法 + $model = $this->parent->$relation(); + $localKey = $this->localKey; + $foreignKey = $this->foreignKey; + switch ($this->type) { + case self::HAS_ONE: + case self::BELONGS_TO: + // 模型关联组装 + $this->match($model, $relation, $result); + break; + case self::HAS_MANY: + case self::BELONGS_TO_MANY: + if (isset($result->$localKey)) { + $data = $this->eagerly($model, [$foreignKey => $result->$localKey], $relation, $subRelation); + // 关联数据封装 + if (!isset($data[$result->$localKey])) { + $data[$result->$localKey] = []; + } + $result->__set($relation, $data[$result->$localKey]); + } + break; + } + } + $this->eagerly = false; + return $result; + } + + /** + * 一对一 关联模型预查询拼装 + * @access public + * @param string $model 模型名称 + * @param string $relation 关联名 + * @param Model $result 模型对象实例 + * @return void + */ + protected function match($model, $relation, &$result) + { + $modelName = strtolower(basename(str_replace('\\', '/', $model))); + // 重新组装模型数据 + foreach ($result->toArray() as $key => $val) { + if (strpos($key, '__')) { + list($name, $attr) = explode('__', $key); + if ($name == $modelName) { + $list[$name][$attr] = $val; + unset($result->$key); + } + } + } + + if (!isset($list[$modelName])) { + // 设置关联模型属性 + $list[$modelName] = []; + } + $result->__set($relation, new $model($list[$modelName])); + } + + /** + * 一对多 关联模型预查询 + * @access public + * @param string $model 模型名称 + * @param array $where 关联预查询条件 + * @param string $relation 关联名 + * @param string $subRelation 子关联 + * @return void + */ + protected function eagerly($model, $where, $relation, $subRelation = '') + { + $foreignKey = $this->foreignKey; + // 预载入关联查询 支持嵌套预载入 + $list = $model::where($where)->with($subRelation)->select(); + + // 组装模型数据 + $data = []; + foreach ($list as $set) { + $data[$set->$foreignKey][] = $set; + } + return $data; + } + + /** + * HAS ONE 关联定义 + * @access public + * @param string $model 模型名 + * @param string $foreignKey 关联外键 + * @param string $localKey 关联主键 + * @return \think\db\Driver|string + */ + public function hasOne($model, $foreignKey = '', $localKey = '') + { + $this->type = self::HAS_ONE; + $this->model = $model; + $this->foreignKey = $foreignKey; + $this->localKey = $localKey; + + if (!$this->eagerly && isset($this->parent->$localKey)) { + // 关联查询封装 + return $model::where($foreignKey, $this->parent->$localKey); + } else { + // 预载入封装 + return $model; + } + } + + /** + * BELONGS TO 关联定义 + * @access public + * @param string $model 模型名 + * @param string $localKey 关联主键 + * @param string $foreignKey 关联外键 + * @return \think\db\Driver|string + */ + public function belongsTo($model, $localKey = '', $foreignKey = '') + { + // 记录当前关联信息 + $this->type = self::BELONGS_TO; + $this->model = $model; + $this->foreignKey = $foreignKey; + $this->localKey = $localKey; + + if (!$this->eagerly && isset($this->parent->$localKey)) { + // 关联查询封装 + return $model::where($foreignKey, $this->parent->$localKey); + } else { + // 预载入封装 + return $model; + } + } + + /** + * HAS MANY 关联定义 + * @access public + * @param string $model 模型名 + * @param string $foreignKey 关联外键 + * @param string $localKey 关联主键 + * @return \think\db\Driver|string + */ + public function hasMany($model, $foreignKey = '', $localKey = '') + { + // 记录当前关联信息 + $this->type = self::HAS_MANY; + $this->model = $model; + $this->foreignKey = $foreignKey; + $this->localKey = $localKey; + + if (!$this->eagerly && isset($this->parent->$localKey)) { + // 关联查询封装 + return $model::where($foreignKey, $this->parent->$localKey); + } else { + // 预载入封装 + return $model; + } + } + + /** + * BELONGS TO MANY 关联定义 + * @access public + * @param string $model 模型名 + * @param string $localKey 关联主键 + * @param string $foreignKey 关联外键 + * @return \think\db\Driver|string + */ + public function belongsToMany($model, $localKey = '', $foreignKey = '') + { + // 记录当前关联信息 + $this->type = self::BELONGS_TO_MANY; + $this->model = $model; + $this->foreignKey = $foreignKey; + $this->localKey = $localKey; + + if (!$this->eagerly && isset($this->parent->$localKey)) { + // 关联查询封装 + return $model::where($foreignKey, $this->parent->$localKey); + } else { + // 预载入封装 + return $model; + } + } + +}