BelongsTo.php 9.7 KB

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