BelongsToMany.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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\Collection;
  13. use think\db\Query;
  14. use think\Exception;
  15. use think\Loader;
  16. use think\Model;
  17. use think\model\Pivot;
  18. use think\model\Relation;
  19. use think\Paginator;
  20. class BelongsToMany extends Relation
  21. {
  22. // 中间表表名
  23. protected $middle;
  24. // 中间表模型名称
  25. protected $pivotName;
  26. // 中间表模型对象
  27. protected $pivot;
  28. /**
  29. * 构造函数
  30. * @access public
  31. * @param Model $parent 上级模型对象
  32. * @param string $model 模型名
  33. * @param string $table 中间表名
  34. * @param string $foreignKey 关联模型外键
  35. * @param string $localKey 当前模型关联键
  36. */
  37. public function __construct(Model $parent, $model, $table, $foreignKey, $localKey)
  38. {
  39. $this->parent = $parent;
  40. $this->model = $model;
  41. $this->foreignKey = $foreignKey;
  42. $this->localKey = $localKey;
  43. if (false !== strpos($table, '\\')) {
  44. $this->pivotName = $table;
  45. $this->middle = basename(str_replace('\\', '/', $table));
  46. } else {
  47. $this->middle = $table;
  48. }
  49. $this->query = (new $model)->db();
  50. $this->pivot = $this->newPivot();
  51. if ('think\model\Pivot' == get_class($this->pivot)) {
  52. $this->pivot->name($this->middle);
  53. }
  54. }
  55. /**
  56. * 设置中间表模型
  57. * @param $pivot
  58. * @return $this
  59. */
  60. public function pivot($pivot)
  61. {
  62. $this->pivotName = $pivot;
  63. return $this;
  64. }
  65. /**
  66. * 实例化中间表模型
  67. * @param $data
  68. * @return Pivot
  69. * @throws Exception
  70. */
  71. protected function newPivot($data = [])
  72. {
  73. $class = $this->pivotName ?: '\\think\\model\\Pivot';
  74. $pivot = new $class($data, $this->parent, $this->middle);
  75. if ($pivot instanceof Pivot) {
  76. return $pivot;
  77. } else {
  78. throw new Exception('pivot model must extends: \think\model\Pivot');
  79. }
  80. }
  81. /**
  82. * 合成中间表模型
  83. * @param array|Collection|Paginator $models
  84. */
  85. protected function hydratePivot($models)
  86. {
  87. foreach ($models as $model) {
  88. $pivot = [];
  89. foreach ($model->getData() as $key => $val) {
  90. if (strpos($key, '__')) {
  91. list($name, $attr) = explode('__', $key, 2);
  92. if ('pivot' == $name) {
  93. $pivot[$attr] = $val;
  94. unset($model->$key);
  95. }
  96. }
  97. }
  98. $model->setRelation('pivot', $this->newPivot($pivot));
  99. }
  100. }
  101. /**
  102. * 创建关联查询Query对象
  103. * @return Query
  104. */
  105. protected function buildQuery()
  106. {
  107. $foreignKey = $this->foreignKey;
  108. $localKey = $this->localKey;
  109. $pk = $this->parent->getPk();
  110. // 关联查询
  111. $condition['pivot.' . $localKey] = $this->parent->$pk;
  112. return $this->belongsToManyQuery($foreignKey, $localKey, $condition);
  113. }
  114. /**
  115. * 延迟获取关联数据
  116. * @param string $subRelation 子关联名
  117. * @param \Closure $closure 闭包查询条件
  118. * @return false|\PDOStatement|string|\think\Collection
  119. */
  120. public function getRelation($subRelation = '', $closure = null)
  121. {
  122. if ($closure) {
  123. call_user_func_array($closure, [ & $this->query]);
  124. }
  125. $result = $this->buildQuery()->relation($subRelation)->select();
  126. $this->hydratePivot($result);
  127. return $result;
  128. }
  129. /**
  130. * 重载select方法
  131. * @param null $data
  132. * @return false|\PDOStatement|string|Collection
  133. */
  134. public function select($data = null)
  135. {
  136. $result = $this->buildQuery()->select($data);
  137. $this->hydratePivot($result);
  138. return $result;
  139. }
  140. /**
  141. * 重载paginate方法
  142. * @param null $listRows
  143. * @param bool $simple
  144. * @param array $config
  145. * @return Paginator
  146. */
  147. public function paginate($listRows = null, $simple = false, $config = [])
  148. {
  149. $result = $this->buildQuery()->paginate($listRows, $simple, $config);
  150. $this->hydratePivot($result);
  151. return $result;
  152. }
  153. /**
  154. * 重载find方法
  155. * @param null $data
  156. * @return array|false|\PDOStatement|string|Model
  157. */
  158. public function find($data = null)
  159. {
  160. $result = $this->buildQuery()->find($data);
  161. if ($result) {
  162. $this->hydratePivot([$result]);
  163. }
  164. return $result;
  165. }
  166. /**
  167. * 查找多条记录 如果不存在则抛出异常
  168. * @access public
  169. * @param array|string|Query|\Closure $data
  170. * @return array|\PDOStatement|string|Model
  171. */
  172. public function selectOrFail($data = null)
  173. {
  174. return $this->failException(true)->select($data);
  175. }
  176. /**
  177. * 查找单条记录 如果不存在则抛出异常
  178. * @access public
  179. * @param array|string|Query|\Closure $data
  180. * @return array|\PDOStatement|string|Model
  181. */
  182. public function findOrFail($data = null)
  183. {
  184. return $this->failException(true)->find($data);
  185. }
  186. /**
  187. * 根据关联条件查询当前模型
  188. * @access public
  189. * @param string $operator 比较操作符
  190. * @param integer $count 个数
  191. * @param string $id 关联表的统计字段
  192. * @param string $joinType JOIN类型
  193. * @return Query
  194. */
  195. public function has($operator = '>=', $count = 1, $id = '*', $joinType = 'INNER')
  196. {
  197. return $this->parent;
  198. }
  199. /**
  200. * 根据关联条件查询当前模型
  201. * @access public
  202. * @param mixed $where 查询条件(数组或者闭包)
  203. * @param mixed $fields 字段
  204. * @return Query
  205. * @throws Exception
  206. */
  207. public function hasWhere($where = [], $fields = null)
  208. {
  209. throw new Exception('relation not support: hasWhere');
  210. }
  211. /**
  212. * 设置中间表的查询条件
  213. * @param $field
  214. * @param null $op
  215. * @param null $condition
  216. * @return $this
  217. */
  218. public function wherePivot($field, $op = null, $condition = null)
  219. {
  220. $field = 'pivot.' . $field;
  221. $this->query->where($field, $op, $condition);
  222. return $this;
  223. }
  224. /**
  225. * 预载入关联查询(数据集)
  226. * @access public
  227. * @param array $resultSet 数据集
  228. * @param string $relation 当前关联名
  229. * @param string $subRelation 子关联名
  230. * @param \Closure $closure 闭包
  231. * @return void
  232. */
  233. public function eagerlyResultSet(&$resultSet, $relation, $subRelation, $closure)
  234. {
  235. $localKey = $this->localKey;
  236. $foreignKey = $this->foreignKey;
  237. $pk = $resultSet[0]->getPk();
  238. $range = [];
  239. foreach ($resultSet as $result) {
  240. // 获取关联外键列表
  241. if (isset($result->$pk)) {
  242. $range[] = $result->$pk;
  243. }
  244. }
  245. if (!empty($range)) {
  246. // 查询关联数据
  247. $data = $this->eagerlyManyToMany([
  248. 'pivot.' . $localKey => [
  249. 'in',
  250. $range,
  251. ],
  252. ], $relation, $subRelation);
  253. // 关联属性名
  254. $attr = Loader::parseName($relation);
  255. // 关联数据封装
  256. foreach ($resultSet as $result) {
  257. if (!isset($data[$result->$pk])) {
  258. $data[$result->$pk] = [];
  259. }
  260. $result->setRelation($attr, $this->resultSetBuild($data[$result->$pk]));
  261. }
  262. }
  263. }
  264. /**
  265. * 预载入关联查询(单个数据)
  266. * @access public
  267. * @param Model $result 数据对象
  268. * @param string $relation 当前关联名
  269. * @param string $subRelation 子关联名
  270. * @param \Closure $closure 闭包
  271. * @return void
  272. */
  273. public function eagerlyResult(&$result, $relation, $subRelation, $closure)
  274. {
  275. $pk = $result->getPk();
  276. if (isset($result->$pk)) {
  277. $pk = $result->$pk;
  278. // 查询管理数据
  279. $data = $this->eagerlyManyToMany(['pivot.' . $this->localKey => $pk], $relation, $subRelation);
  280. // 关联数据封装
  281. if (!isset($data[$pk])) {
  282. $data[$pk] = [];
  283. }
  284. $result->setRelation(Loader::parseName($relation), $this->resultSetBuild($data[$pk]));
  285. }
  286. }
  287. /**
  288. * 关联统计
  289. * @access public
  290. * @param Model $result 数据对象
  291. * @param \Closure $closure 闭包
  292. * @return integer
  293. */
  294. public function relationCount($result, $closure)
  295. {
  296. $pk = $result->getPk();
  297. $count = 0;
  298. if (isset($result->$pk)) {
  299. $pk = $result->$pk;
  300. $count = $this->belongsToManyQuery($this->foreignKey, $this->localKey, ['pivot.' . $this->localKey => $pk])->count();
  301. }
  302. return $count;
  303. }
  304. /**
  305. * 获取关联统计子查询
  306. * @access public
  307. * @param \Closure $closure 闭包
  308. * @return string
  309. */
  310. public function getRelationCountQuery($closure)
  311. {
  312. return $this->belongsToManyQuery($this->foreignKey, $this->localKey, [
  313. 'pivot.' . $this->localKey => [
  314. 'exp',
  315. '=' . $this->parent->getTable() . '.' . $this->parent->getPk(),
  316. ],
  317. ])->fetchSql()->count();
  318. }
  319. /**
  320. * 多对多 关联模型预查询
  321. * @access public
  322. * @param array $where 关联预查询条件
  323. * @param string $relation 关联名
  324. * @param string $subRelation 子关联
  325. * @return array
  326. */
  327. protected function eagerlyManyToMany($where, $relation, $subRelation = '')
  328. {
  329. // 预载入关联查询 支持嵌套预载入
  330. $list = $this->belongsToManyQuery($this->foreignKey, $this->localKey, $where)->with($subRelation)->select();
  331. // 组装模型数据
  332. $data = [];
  333. foreach ($list as $set) {
  334. $pivot = [];
  335. foreach ($set->getData() as $key => $val) {
  336. if (strpos($key, '__')) {
  337. list($name, $attr) = explode('__', $key, 2);
  338. if ('pivot' == $name) {
  339. $pivot[$attr] = $val;
  340. unset($set->$key);
  341. }
  342. }
  343. }
  344. $set->setRelation('pivot', $this->newPivot($pivot));
  345. $data[$pivot[$this->localKey]][] = $set;
  346. }
  347. return $data;
  348. }
  349. /**
  350. * BELONGS TO MANY 关联查询
  351. * @access public
  352. * @param string $foreignKey 关联模型关联键
  353. * @param string $localKey 当前模型关联键
  354. * @param array $condition 关联查询条件
  355. * @return Query
  356. */
  357. protected function belongsToManyQuery($foreignKey, $localKey, $condition = [])
  358. {
  359. // 关联查询封装
  360. $tableName = $this->query->getTable();
  361. $table = $this->pivot->getTable();
  362. $fields = $this->getQueryFields($tableName);
  363. $query = $this->query->field($fields)
  364. ->field(true, false, $table, 'pivot', 'pivot__');
  365. if (empty($this->baseQuery)) {
  366. $relationFk = $this->query->getPk();
  367. $query->join([$table => 'pivot'], 'pivot.' . $foreignKey . '=' . $tableName . '.' . $relationFk)
  368. ->where($condition);
  369. }
  370. return $query;
  371. }
  372. /**
  373. * 保存(新增)当前关联数据对象
  374. * @access public
  375. * @param mixed $data 数据 可以使用数组 关联模型对象 和 关联对象的主键
  376. * @param array $pivot 中间表额外数据
  377. * @return integer
  378. */
  379. public function save($data, array $pivot = [])
  380. {
  381. // 保存关联表/中间表数据
  382. return $this->attach($data, $pivot);
  383. }
  384. /**
  385. * 批量保存当前关联数据对象
  386. * @access public
  387. * @param array $dataSet 数据集
  388. * @param array $pivot 中间表额外数据
  389. * @param bool $samePivot 额外数据是否相同
  390. * @return integer
  391. */
  392. public function saveAll(array $dataSet, array $pivot = [], $samePivot = false)
  393. {
  394. $result = false;
  395. foreach ($dataSet as $key => $data) {
  396. if (!$samePivot) {
  397. $pivotData = isset($pivot[$key]) ? $pivot[$key] : [];
  398. } else {
  399. $pivotData = $pivot;
  400. }
  401. $result = $this->attach($data, $pivotData);
  402. }
  403. return $result;
  404. }
  405. /**
  406. * 附加关联的一个中间表数据
  407. * @access public
  408. * @param mixed $data 数据 可以使用数组、关联模型对象 或者 关联对象的主键
  409. * @param array $pivot 中间表额外数据
  410. * @return array|Pivot
  411. * @throws Exception
  412. */
  413. public function attach($data, $pivot = [])
  414. {
  415. if (is_array($data)) {
  416. if (key($data) === 0) {
  417. $id = $data;
  418. } else {
  419. // 保存关联表数据
  420. $model = new $this->model;
  421. $model->save($data);
  422. $id = $model->getLastInsID();
  423. }
  424. } elseif (is_numeric($data) || is_string($data)) {
  425. // 根据关联表主键直接写入中间表
  426. $id = $data;
  427. } elseif ($data instanceof Model) {
  428. // 根据关联表主键直接写入中间表
  429. $relationFk = $data->getPk();
  430. $id = $data->$relationFk;
  431. }
  432. if ($id) {
  433. // 保存中间表数据
  434. $pk = $this->parent->getPk();
  435. $pivot[$this->localKey] = $this->parent->$pk;
  436. $ids = (array) $id;
  437. foreach ($ids as $id) {
  438. $pivot[$this->foreignKey] = $id;
  439. $this->pivot->insert($pivot, true);
  440. $result[] = $this->newPivot($pivot);
  441. }
  442. if (count($result) == 1) {
  443. // 返回中间表模型对象
  444. $result = $result[0];
  445. }
  446. return $result;
  447. } else {
  448. throw new Exception('miss relation data');
  449. }
  450. }
  451. /**
  452. * 解除关联的一个中间表数据
  453. * @access public
  454. * @param integer|array $data 数据 可以使用关联对象的主键
  455. * @param bool $relationDel 是否同时删除关联表数据
  456. * @return integer
  457. */
  458. public function detach($data = null, $relationDel = false)
  459. {
  460. if (is_array($data)) {
  461. $id = $data;
  462. } elseif (is_numeric($data) || is_string($data)) {
  463. // 根据关联表主键直接写入中间表
  464. $id = $data;
  465. } elseif ($data instanceof Model) {
  466. // 根据关联表主键直接写入中间表
  467. $relationFk = $data->getPk();
  468. $id = $data->$relationFk;
  469. }
  470. // 删除中间表数据
  471. $pk = $this->parent->getPk();
  472. $pivot[$this->localKey] = $this->parent->$pk;
  473. if (isset($id)) {
  474. $pivot[$this->foreignKey] = is_array($id) ? ['in', $id] : $id;
  475. }
  476. $this->pivot->where($pivot)->delete();
  477. // 删除关联表数据
  478. if (isset($id) && $relationDel) {
  479. $model = $this->model;
  480. $model::destroy($id);
  481. }
  482. }
  483. /**
  484. * 数据同步
  485. * @param array $ids
  486. * @param bool $detaching
  487. * @return array
  488. */
  489. public function sync($ids, $detaching = true)
  490. {
  491. $changes = [
  492. 'attached' => [],
  493. 'detached' => [],
  494. 'updated' => [],
  495. ];
  496. $pk = $this->parent->getPk();
  497. $current = $this->pivot->where($this->localKey, $this->parent->$pk)
  498. ->column($this->foreignKey);
  499. $records = [];
  500. foreach ($ids as $key => $value) {
  501. if (!is_array($value)) {
  502. $records[$value] = [];
  503. } else {
  504. $records[$key] = $value;
  505. }
  506. }
  507. $detach = array_diff($current, array_keys($records));
  508. if ($detaching && count($detach) > 0) {
  509. $this->detach($detach);
  510. $changes['detached'] = $detach;
  511. }
  512. foreach ($records as $id => $attributes) {
  513. if (!in_array($id, $current)) {
  514. $this->attach($id, $attributes);
  515. $changes['attached'][] = $id;
  516. } elseif (count($attributes) > 0 &&
  517. $this->attach($id, $attributes)
  518. ) {
  519. $changes['updated'][] = $id;
  520. }
  521. }
  522. return $changes;
  523. }
  524. /**
  525. * 执行基础查询(进执行一次)
  526. * @access protected
  527. * @return void
  528. */
  529. protected function baseQuery()
  530. {
  531. if (empty($this->baseQuery) && $this->parent->getData()) {
  532. $pk = $this->parent->getPk();
  533. $table = $this->pivot->getTable();
  534. $this->query->join([$table => 'pivot'], 'pivot.' . $this->foreignKey . '=' . $this->query->getTable() . '.' . $this->query->getPk())->where('pivot.' . $this->localKey, $this->parent->$pk);
  535. $this->baseQuery = true;
  536. }
  537. }
  538. }