0
0

MorphMany.php 9.6 KB

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