HasOne.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\model\relation;
  12. use Closure;
  13. use think\db\Query;
  14. use think\Loader;
  15. use think\Model;
  16. class HasOne extends OneToOne
  17. {
  18. /**
  19. * 架构函数
  20. * @access public
  21. * @param Model $parent 上级模型对象
  22. * @param string $model 模型名
  23. * @param string $foreignKey 关联外键
  24. * @param string $localKey 当前模型主键
  25. */
  26. public function __construct(Model $parent, $model, $foreignKey, $localKey)
  27. {
  28. $this->parent = $parent;
  29. $this->model = $model;
  30. $this->foreignKey = $foreignKey;
  31. $this->localKey = $localKey;
  32. $this->joinType = 'INNER';
  33. $this->query = (new $model)->db();
  34. if (get_class($parent) == $model) {
  35. $this->selfRelation = true;
  36. }
  37. }
  38. /**
  39. * 延迟获取关联数据
  40. * @access public
  41. * @param string $subRelation 子关联名
  42. * @param \Closure $closure 闭包查询条件
  43. * @return Model
  44. */
  45. public function getRelation($subRelation = '', $closure = null)
  46. {
  47. $localKey = $this->localKey;
  48. if ($closure instanceof Closure) {
  49. $closure($this->query);
  50. }
  51. // 判断关联类型执行查询
  52. $relationModel = $this->query
  53. ->removeWhereField($this->foreignKey)
  54. ->where($this->foreignKey, $this->parent->$localKey)
  55. ->relation($subRelation)
  56. ->find();
  57. if ($relationModel) {
  58. $relationModel->setParent(clone $this->parent);
  59. }
  60. return $relationModel;
  61. }
  62. /**
  63. * 创建关联统计子查询
  64. * @access public
  65. * @param \Closure $closure 闭包
  66. * @param string $aggregate 聚合查询方法
  67. * @param string $field 字段
  68. * @param string $aggregateAlias 聚合字段别名
  69. * @return string
  70. */
  71. public function getRelationCountQuery($closure, $aggregate = 'count', $field = '*', &$aggregateAlias = '')
  72. {
  73. if ($closure instanceof Closure) {
  74. $return = $closure($this->query);
  75. if ($return && is_string($return)) {
  76. $aggregateAlias = $return;
  77. }
  78. }
  79. return $this->query
  80. ->whereExp($this->foreignKey, '=' . $this->parent->getTable() . '.' . $this->localKey)
  81. ->fetchSql()
  82. ->$aggregate($field);
  83. }
  84. /**
  85. * 关联统计
  86. * @access public
  87. * @param Model $result 数据对象
  88. * @param \Closure $closure 闭包
  89. * @param string $aggregate 聚合查询方法
  90. * @param string $field 字段
  91. * @param string $name 统计字段别名
  92. * @return integer
  93. */
  94. public function relationCount($result, $closure, $aggregate = 'count', $field = '*', &$name = '')
  95. {
  96. $localKey = $this->localKey;
  97. if (!isset($result->$localKey)) {
  98. return 0;
  99. }
  100. if ($closure instanceof Closure) {
  101. $return = $closure($this->query);
  102. if ($return && is_string($return)) {
  103. $name = $return;
  104. }
  105. }
  106. return $this->query
  107. ->where($this->foreignKey, '=', $result->$localKey)
  108. ->$aggregate($field);
  109. }
  110. /**
  111. * 根据关联条件查询当前模型
  112. * @access public
  113. * @param string $operator 比较操作符
  114. * @param integer $count 个数
  115. * @param string $id 关联表的统计字段
  116. * @param string $joinType JOIN类型
  117. * @return Query
  118. */
  119. public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER')
  120. {
  121. $table = $this->query->getTable();
  122. $model = basename(str_replace('\\', '/', get_class($this->parent)));
  123. $relation = basename(str_replace('\\', '/', $this->model));
  124. $localKey = $this->localKey;
  125. $foreignKey = $this->foreignKey;
  126. $softDelete = $this->query->getOptions('soft_delete');
  127. return $this->parent->db()
  128. ->alias($model)
  129. ->whereExists(function ($query) use ($table, $model, $relation, $localKey, $foreignKey, $softDelete) {
  130. $query->table([$table => $relation])
  131. ->field($relation . '.' . $foreignKey)
  132. ->whereExp($model . '.' . $localKey, '=' . $relation . '.' . $foreignKey)
  133. ->when($softDelete, function ($query) use ($softDelete, $relation) {
  134. $query->where($relation . strstr($softDelete[0], '.'), '=' == $softDelete[1][0] ? $softDelete[1][1] : null);
  135. });
  136. });
  137. }
  138. /**
  139. * 根据关联条件查询当前模型
  140. * @access public
  141. * @param mixed $where 查询条件(数组或者闭包)
  142. * @param mixed $fields 字段
  143. * @return Query
  144. */
  145. public function hasWhere($where = [], $fields = null)
  146. {
  147. $table = $this->query->getTable();
  148. $model = basename(str_replace('\\', '/', get_class($this->parent)));
  149. $relation = basename(str_replace('\\', '/', $this->model));
  150. if (is_array($where)) {
  151. $this->getQueryWhere($where, $relation);
  152. }
  153. $fields = $this->getRelationQueryFields($fields, $model);
  154. $softDelete = $this->query->getOptions('soft_delete');
  155. return $this->parent->db()
  156. ->alias($model)
  157. ->field($fields)
  158. ->join([$table => $relation], $model . '.' . $this->localKey . '=' . $relation . '.' . $this->foreignKey, $this->joinType)
  159. ->when($softDelete, function ($query) use ($softDelete, $relation) {
  160. $query->where($relation . strstr($softDelete[0], '.'), '=' == $softDelete[1][0] ? $softDelete[1][1] : null);
  161. })
  162. ->where($where);
  163. }
  164. /**
  165. * 预载入关联查询(数据集)
  166. * @access protected
  167. * @param array $resultSet 数据集
  168. * @param string $relation 当前关联名
  169. * @param string $subRelation 子关联名
  170. * @param \Closure $closure 闭包
  171. * @return void
  172. */
  173. protected function eagerlySet(&$resultSet, $relation, $subRelation, $closure)
  174. {
  175. $localKey = $this->localKey;
  176. $foreignKey = $this->foreignKey;
  177. $range = [];
  178. foreach ($resultSet as $result) {
  179. // 获取关联外键列表
  180. if (isset($result->$localKey)) {
  181. $range[] = $result->$localKey;
  182. }
  183. }
  184. if (!empty($range)) {
  185. $this->query->removeWhereField($foreignKey);
  186. $data = $this->eagerlyWhere([
  187. [$foreignKey, 'in', $range],
  188. ], $foreignKey, $relation, $subRelation, $closure);
  189. // 关联属性名
  190. $attr = Loader::parseName($relation);
  191. // 关联数据封装
  192. foreach ($resultSet as $result) {
  193. // 关联模型
  194. if (!isset($data[$result->$localKey])) {
  195. $relationModel = null;
  196. } else {
  197. $relationModel = $data[$result->$localKey];
  198. $relationModel->setParent(clone $result);
  199. $relationModel->isUpdate(true);
  200. }
  201. if (!empty($this->bindAttr)) {
  202. // 绑定关联属性
  203. $this->bindAttr($relationModel, $result, $this->bindAttr);
  204. } else {
  205. // 设置关联属性
  206. $result->setRelation($attr, $relationModel);
  207. }
  208. }
  209. }
  210. }
  211. /**
  212. * 预载入关联查询(数据)
  213. * @access protected
  214. * @param Model $result 数据对象
  215. * @param string $relation 当前关联名
  216. * @param string $subRelation 子关联名
  217. * @param \Closure $closure 闭包
  218. * @return void
  219. */
  220. protected function eagerlyOne(&$result, $relation, $subRelation, $closure)
  221. {
  222. $localKey = $this->localKey;
  223. $foreignKey = $this->foreignKey;
  224. $this->query->removeWhereField($foreignKey);
  225. $data = $this->eagerlyWhere([
  226. [$foreignKey, '=', $result->$localKey],
  227. ], $foreignKey, $relation, $subRelation, $closure);
  228. // 关联模型
  229. if (!isset($data[$result->$localKey])) {
  230. $relationModel = null;
  231. } else {
  232. $relationModel = $data[$result->$localKey];
  233. $relationModel->setParent(clone $result);
  234. $relationModel->isUpdate(true);
  235. }
  236. if (!empty($this->bindAttr)) {
  237. // 绑定关联属性
  238. $this->bindAttr($relationModel, $result, $this->bindAttr);
  239. } else {
  240. $result->setRelation(Loader::parseName($relation), $relationModel);
  241. }
  242. }
  243. /**
  244. * 执行基础查询(仅执行一次)
  245. * @access protected
  246. * @return void
  247. */
  248. protected function baseQuery()
  249. {
  250. if (empty($this->baseQuery)) {
  251. if (isset($this->parent->{$this->localKey})) {
  252. // 关联查询带入关联条件
  253. $this->query->where($this->foreignKey, '=', $this->parent->{$this->localKey});
  254. }
  255. $this->baseQuery = true;
  256. }
  257. }
  258. }