BelongsTo.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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\Loader;
  14. use think\Model;
  15. class BelongsTo extends OneToOne
  16. {
  17. /**
  18. * 架构函数
  19. * @access public
  20. * @param Model $parent 上级模型对象
  21. * @param string $model 模型名
  22. * @param string $foreignKey 关联外键
  23. * @param string $localKey 关联主键
  24. * @param string $relation 关联名
  25. */
  26. public function __construct(Model $parent, $model, $foreignKey, $localKey, $relation = null)
  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. $this->relation = $relation;
  35. if (get_class($parent) == $model) {
  36. $this->selfRelation = true;
  37. }
  38. }
  39. /**
  40. * 延迟获取关联数据
  41. * @access public
  42. * @param string $subRelation 子关联名
  43. * @param \Closure $closure 闭包查询条件
  44. * @return Model
  45. */
  46. public function getRelation($subRelation = '', $closure = null)
  47. {
  48. if ($closure instanceof Closure) {
  49. $closure($this->query);
  50. }
  51. $foreignKey = $this->foreignKey;
  52. $relationModel = $this->query
  53. ->removeWhereField($this->localKey)
  54. ->where($this->localKey, $this->parent->$foreignKey)
  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->localKey, '=' . $this->parent->getTable() . '.' . $this->foreignKey)
  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. $foreignKey = $this->foreignKey;
  97. if (!isset($result->$foreignKey)) {
  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->localKey, '=', $result->$foreignKey)
  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) {
  130. $query->table([$table => $relation])
  131. ->field($relation . '.' . $localKey)
  132. ->whereExp($model . '.' . $foreignKey, '=' . $relation . '.' . $localKey)
  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->foreignKey . '=' . $relation . '.' . $this->localKey, $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->$foreignKey)) {
  181. $range[] = $result->$foreignKey;
  182. }
  183. }
  184. if (!empty($range)) {
  185. $this->query->removeWhereField($localKey);
  186. $data = $this->eagerlyWhere([
  187. [$localKey, 'in', $range],
  188. ], $localKey, $relation, $subRelation, $closure);
  189. // 关联属性名
  190. $attr = Loader::parseName($relation);
  191. // 关联数据封装
  192. foreach ($resultSet as $result) {
  193. // 关联模型
  194. if (!isset($data[$result->$foreignKey])) {
  195. $relationModel = null;
  196. } else {
  197. $relationModel = $data[$result->$foreignKey];
  198. $relationModel->setParent(clone $result);
  199. $relationModel->isUpdate(true);
  200. }
  201. if (!empty($this->bindAttr)) {
  202. // 绑定关联属性
  203. $this->bindAttr($relationModel, $result);
  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($localKey);
  225. $data = $this->eagerlyWhere([
  226. [$localKey, '=', $result->$foreignKey],
  227. ], $localKey, $relation, $subRelation, $closure);
  228. // 关联模型
  229. if (!isset($data[$result->$foreignKey])) {
  230. $relationModel = null;
  231. } else {
  232. $relationModel = $data[$result->$foreignKey];
  233. $relationModel->setParent(clone $result);
  234. $relationModel->isUpdate(true);
  235. }
  236. if (!empty($this->bindAttr)) {
  237. // 绑定关联属性
  238. $this->bindAttr($relationModel, $result);
  239. } else {
  240. // 设置关联属性
  241. $result->setRelation(Loader::parseName($relation), $relationModel);
  242. }
  243. }
  244. /**
  245. * 添加关联数据
  246. * @access public
  247. * @param Model $model 关联模型对象
  248. * @return Model
  249. */
  250. public function associate($model)
  251. {
  252. $this->parent->setAttr($this->foreignKey, $model->getKey());
  253. $this->parent->save();
  254. return $this->parent->setRelation($this->relation, $model);
  255. }
  256. /**
  257. * 注销关联数据
  258. * @access public
  259. * @return Model
  260. */
  261. public function dissociate()
  262. {
  263. $this->parent->setAttr($this->foreignKey, null);
  264. $this->parent->save();
  265. return $this->parent->setRelation($this->relation, null);
  266. }
  267. /**
  268. * 执行基础查询(仅执行一次)
  269. * @access protected
  270. * @return void
  271. */
  272. protected function baseQuery()
  273. {
  274. if (empty($this->baseQuery)) {
  275. if (isset($this->parent->{$this->foreignKey})) {
  276. // 关联查询带入关联条件
  277. $this->query->where($this->localKey, '=', $this->parent->{$this->foreignKey});
  278. }
  279. $this->baseQuery = true;
  280. }
  281. }
  282. }