HasMany.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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\db\Query;
  13. use think\Loader;
  14. use think\Model;
  15. use think\model\Relation;
  16. class HasMany extends Relation
  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->query = (new $model)->db();
  33. }
  34. /**
  35. * 延迟获取关联数据
  36. * @param string $subRelation 子关联名
  37. * @param \Closure $closure 闭包查询条件
  38. * @return false|\PDOStatement|string|\think\Collection
  39. */
  40. public function getRelation($subRelation = '', $closure = null)
  41. {
  42. if ($closure) {
  43. call_user_func_array($closure, [ & $this->query]);
  44. }
  45. $list = $this->relation($subRelation)->select();
  46. $parent = clone $this->parent;
  47. foreach ($list as &$model) {
  48. $model->setParent($parent);
  49. }
  50. return $list;
  51. }
  52. /**
  53. * 预载入关联查询
  54. * @access public
  55. * @param array $resultSet 数据集
  56. * @param string $relation 当前关联名
  57. * @param string $subRelation 子关联名
  58. * @param \Closure $closure 闭包
  59. * @return void
  60. */
  61. public function eagerlyResultSet(&$resultSet, $relation, $subRelation, $closure)
  62. {
  63. $localKey = $this->localKey;
  64. $range = [];
  65. foreach ($resultSet as $result) {
  66. // 获取关联外键列表
  67. if (isset($result->$localKey)) {
  68. $range[] = $result->$localKey;
  69. }
  70. }
  71. if (!empty($range)) {
  72. $data = $this->eagerlyOneToMany($this->query, [
  73. $this->foreignKey => [
  74. 'in',
  75. $range,
  76. ],
  77. ], $relation, $subRelation, $closure);
  78. // 关联属性名
  79. $attr = Loader::parseName($relation);
  80. // 关联数据封装
  81. foreach ($resultSet as $result) {
  82. if (!isset($data[$result->$localKey])) {
  83. $data[$result->$localKey] = [];
  84. }
  85. foreach ($data[$result->$localKey] as &$relationModel) {
  86. $relationModel->setParent(clone $result);
  87. }
  88. $result->setRelation($attr, $this->resultSetBuild($data[$result->$localKey]));
  89. }
  90. }
  91. }
  92. /**
  93. * 预载入关联查询
  94. * @access public
  95. * @param Model $result 数据对象
  96. * @param string $relation 当前关联名
  97. * @param string $subRelation 子关联名
  98. * @param \Closure $closure 闭包
  99. * @return void
  100. */
  101. public function eagerlyResult(&$result, $relation, $subRelation, $closure)
  102. {
  103. $localKey = $this->localKey;
  104. if (isset($result->$localKey)) {
  105. $data = $this->eagerlyOneToMany($this->query, [$this->foreignKey => $result->$localKey], $relation, $subRelation, $closure);
  106. // 关联数据封装
  107. if (!isset($data[$result->$localKey])) {
  108. $data[$result->$localKey] = [];
  109. }
  110. foreach ($data[$result->$localKey] as &$relationModel) {
  111. $relationModel->setParent(clone $result);
  112. }
  113. $result->setRelation(Loader::parseName($relation), $this->resultSetBuild($data[$result->$localKey]));
  114. }
  115. }
  116. /**
  117. * 关联统计
  118. * @access public
  119. * @param Model $result 数据对象
  120. * @param \Closure $closure 闭包
  121. * @return integer
  122. */
  123. public function relationCount($result, $closure)
  124. {
  125. $localKey = $this->localKey;
  126. $count = 0;
  127. if (isset($result->$localKey)) {
  128. if ($closure) {
  129. call_user_func_array($closure, [ & $this->query]);
  130. }
  131. $count = $this->query->where($this->foreignKey, $result->$localKey)->count();
  132. }
  133. return $count;
  134. }
  135. /**
  136. * 创建关联统计子查询
  137. * @access public
  138. * @param \Closure $closure 闭包
  139. * @param string $name 统计数据别名
  140. * @return string
  141. */
  142. public function getRelationCountQuery($closure, &$name = null)
  143. {
  144. if ($closure) {
  145. $return = call_user_func_array($closure, [ & $this->query]);
  146. if ($return && is_string($return)) {
  147. $name = $return;
  148. }
  149. }
  150. $localKey = $this->localKey ?: $this->parent->getPk();
  151. return $this->query->whereExp($this->foreignKey, '=' . $this->parent->getTable() . '.' . $localKey)->fetchSql()->count();
  152. }
  153. /**
  154. * 一对多 关联模型预查询
  155. * @access public
  156. * @param object $model 关联模型对象
  157. * @param array $where 关联预查询条件
  158. * @param string $relation 关联名
  159. * @param string $subRelation 子关联
  160. * @param bool $closure
  161. * @return array
  162. */
  163. protected function eagerlyOneToMany($model, $where, $relation, $subRelation = '', $closure = false)
  164. {
  165. $foreignKey = $this->foreignKey;
  166. // 预载入关联查询 支持嵌套预载入
  167. if ($closure) {
  168. call_user_func_array($closure, [ & $model]);
  169. }
  170. $list = $model->removeWhereField($foreignKey)->where($where)->with($subRelation)->select();
  171. // 组装模型数据
  172. $data = [];
  173. foreach ($list as $set) {
  174. $data[$set->$foreignKey][] = $set;
  175. }
  176. return $data;
  177. }
  178. /**
  179. * 保存(新增)当前关联数据对象
  180. * @access public
  181. * @param mixed $data 数据 可以使用数组 关联模型对象 和 关联对象的主键
  182. * @return Model|false
  183. */
  184. public function save($data)
  185. {
  186. if ($data instanceof Model) {
  187. $data = $data->getData();
  188. }
  189. // 保存关联表数据
  190. $data[$this->foreignKey] = $this->parent->{$this->localKey};
  191. $model = new $this->model();
  192. return $model->save($data) ? $model : false;
  193. }
  194. /**
  195. * 创建关联对象实例
  196. * @param array $data
  197. * @return Model
  198. */
  199. public function make($data = [])
  200. {
  201. if ($data instanceof Model) {
  202. $data = $data->getData();
  203. }
  204. // 保存关联表数据
  205. $data[$this->foreignKey] = $this->parent->{$this->localKey};
  206. return new $this->model($data);
  207. }
  208. /**
  209. * 批量保存当前关联数据对象
  210. * @access public
  211. * @param array $dataSet 数据集
  212. * @return integer
  213. */
  214. public function saveAll(array $dataSet)
  215. {
  216. $result = false;
  217. foreach ($dataSet as $key => $data) {
  218. $result = $this->save($data);
  219. }
  220. return $result;
  221. }
  222. /**
  223. * 根据关联条件查询当前模型
  224. * @access public
  225. * @param string $operator 比较操作符
  226. * @param integer $count 个数
  227. * @param string $id 关联表的统计字段
  228. * @param string $joinType JOIN类型
  229. * @return Query
  230. */
  231. public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER')
  232. {
  233. $table = $this->query->getTable();
  234. $model = basename(str_replace('\\', '/', get_class($this->parent)));
  235. $relation = basename(str_replace('\\', '/', $this->model));
  236. return $this->parent->db()
  237. ->alias($model)
  238. ->field($model . '.*')
  239. ->join([$table => $relation], $model . '.' . $this->localKey . '=' . $relation . '.' . $this->foreignKey, $joinType)
  240. ->group($relation . '.' . $this->foreignKey)
  241. ->having('count(' . $id . ')' . $operator . $count);
  242. }
  243. /**
  244. * 根据关联条件查询当前模型
  245. * @access public
  246. * @param mixed $where 查询条件(数组或者闭包)
  247. * @param mixed $fields 字段
  248. * @return Query
  249. */
  250. public function hasWhere($where = [], $fields = null)
  251. {
  252. $table = $this->query->getTable();
  253. $model = basename(str_replace('\\', '/', get_class($this->parent)));
  254. $relation = basename(str_replace('\\', '/', $this->model));
  255. if (is_array($where)) {
  256. foreach ($where as $key => $val) {
  257. if (false === strpos($key, '.')) {
  258. $where[$relation . '.' . $key] = $val;
  259. unset($where[$key]);
  260. }
  261. }
  262. }
  263. $fields = $this->getRelationQueryFields($fields, $model);
  264. return $this->parent->db()->alias($model)
  265. ->field($fields)
  266. ->group($model . '.' . $this->localKey)
  267. ->join([$table => $relation], $model . '.' . $this->localKey . '=' . $relation . '.' . $this->foreignKey)
  268. ->where($where);
  269. }
  270. /**
  271. * 执行基础查询(进执行一次)
  272. * @access protected
  273. * @return void
  274. */
  275. protected function baseQuery()
  276. {
  277. if (empty($this->baseQuery)) {
  278. if (isset($this->parent->{$this->localKey})) {
  279. // 关联查询带入关联条件
  280. $this->query->where($this->foreignKey, $this->parent->{$this->localKey});
  281. }
  282. $this->baseQuery = true;
  283. }
  284. }
  285. }