RelationModel.class.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2014 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;
  12. use Think\Model;
  13. /**
  14. * ThinkPHP关联模型扩展
  15. */
  16. class RelationModel extends Model
  17. {
  18. const HAS_ONE = 1;
  19. const BELONGS_TO = 2;
  20. const HAS_MANY = 3;
  21. const MANY_TO_MANY = 4;
  22. // 关联定义
  23. protected $_link = array();
  24. /**
  25. * 动态方法实现
  26. * @access public
  27. * @param string $method 方法名称
  28. * @param array $args 调用参数
  29. * @return mixed
  30. */
  31. public function __call($method, $args)
  32. {
  33. if (strtolower(substr($method, 0, 8)) == 'relation') {
  34. $type = strtoupper(substr($method, 8));
  35. if (in_array($type, array('ADD', 'SAVE', 'DEL'), true)) {
  36. array_unshift($args, $type);
  37. return call_user_func_array(array(&$this, 'opRelation'), $args);
  38. }
  39. } else {
  40. return parent::__call($method, $args);
  41. }
  42. }
  43. /**
  44. * 得到关联的数据表名
  45. * @access public
  46. * @return string
  47. */
  48. public function getRelationTableName($relation)
  49. {
  50. $relationTable = !empty($this->tablePrefix) ? $this->tablePrefix : '';
  51. $relationTable .= $this->tableName ? $this->tableName : $this->name;
  52. $relationTable .= '_' . $relation->getModelName();
  53. return strtolower($relationTable);
  54. }
  55. // 查询成功后的回调方法
  56. protected function _after_find(&$result, $options)
  57. {
  58. // 获取关联数据 并附加到结果中
  59. if (!empty($options['link'])) {
  60. $this->getRelation($result, $options['link']);
  61. }
  62. }
  63. // 查询数据集成功后的回调方法
  64. protected function _after_select(&$result, $options)
  65. {
  66. // 获取关联数据 并附加到结果中
  67. if (!empty($options['link'])) {
  68. $this->getRelations($result, $options['link']);
  69. }
  70. }
  71. // 写入成功后的回调方法
  72. protected function _after_insert($data, $options)
  73. {
  74. // 关联写入
  75. if (!empty($options['link'])) {
  76. $this->opRelation('ADD', $data, $options['link']);
  77. }
  78. }
  79. // 更新成功后的回调方法
  80. protected function _after_update($data, $options)
  81. {
  82. // 关联更新
  83. if (!empty($options['link'])) {
  84. $this->opRelation('SAVE', $data, $options['link']);
  85. }
  86. }
  87. // 删除成功后的回调方法
  88. protected function _after_delete($data, $options)
  89. {
  90. // 关联删除
  91. if (!empty($options['link'])) {
  92. $this->opRelation('DEL', $data, $options['link']);
  93. }
  94. }
  95. /**
  96. * 对保存到数据库的数据进行处理
  97. * @access protected
  98. * @param mixed $data 要操作的数据
  99. * @return boolean
  100. */
  101. protected function _facade($data)
  102. {
  103. $this->_before_write($data);
  104. return $data;
  105. }
  106. /**
  107. * 获取返回数据集的关联记录
  108. * @access protected
  109. * @param array $resultSet 返回数据
  110. * @param string|array $name 关联名称
  111. * @return array
  112. */
  113. protected function getRelations(&$resultSet, $name = '')
  114. {
  115. // 获取记录集的主键列表
  116. foreach ($resultSet as $key => $val) {
  117. $val = $this->getRelation($val, $name);
  118. $resultSet[$key] = $val;
  119. }
  120. return $resultSet;
  121. }
  122. /**
  123. * 获取返回数据的关联记录
  124. * @access protected
  125. * @param mixed $result 返回数据
  126. * @param string|array $name 关联名称
  127. * @param boolean $return 是否返回关联数据本身
  128. * @return array
  129. */
  130. protected function getRelation(&$result, $name = '', $return = false)
  131. {
  132. if (!empty($this->_link)) {
  133. foreach ($this->_link as $key => $val) {
  134. $mappingName = !empty($val['mapping_name']) ? $val['mapping_name'] : $key; // 映射名称
  135. if (empty($name) || true === $name || $mappingName == $name || (is_array($name) && in_array($mappingName, $name))) {
  136. $mappingType = !empty($val['mapping_type']) ? $val['mapping_type'] : $val; // 关联类型
  137. $mappingClass = !empty($val['class_name']) ? $val['class_name'] : $key; // 关联类名
  138. $mappingFields = !empty($val['mapping_fields']) ? $val['mapping_fields'] : '*'; // 映射字段
  139. $mappingCondition = !empty($val['condition']) ? $val['condition'] : '1=1'; // 关联条件
  140. $mappingKey = !empty($val['mapping_key']) ? $val['mapping_key'] : $this->getPk(); // 关联键名
  141. if (strtoupper($mappingClass) == strtoupper($this->name)) {
  142. // 自引用关联 获取父键名
  143. $mappingFk = !empty($val['parent_key']) ? $val['parent_key'] : 'parent_id';
  144. } else {
  145. $mappingFk = !empty($val['foreign_key']) ? $val['foreign_key'] : strtolower($this->name) . '_id'; // 关联外键
  146. }
  147. // 获取关联模型对象
  148. $model = D($mappingClass);
  149. switch ($mappingType) {
  150. case self::HAS_ONE:
  151. $pk = $result[$mappingKey];
  152. $mappingCondition .= " AND {$mappingFk}='{$pk}'";
  153. $relationData = $model->where($mappingCondition)->field($mappingFields)->find();
  154. if (!empty($val['relation_deep'])) {
  155. $model->getRelation($relationData, $val['relation_deep']);
  156. }
  157. break;
  158. case self::BELONGS_TO:
  159. if (strtoupper($mappingClass) == strtoupper($this->name)) {
  160. // 自引用关联 获取父键名
  161. $mappingFk = !empty($val['parent_key']) ? $val['parent_key'] : 'parent_id';
  162. } else {
  163. $mappingFk = !empty($val['foreign_key']) ? $val['foreign_key'] : strtolower($model->getModelName()) . '_id'; // 关联外键
  164. }
  165. $fk = $result[$mappingFk];
  166. $mappingCondition .= " AND {$model->getPk()}='{$fk}'";
  167. $relationData = $model->where($mappingCondition)->field($mappingFields)->find();
  168. if (!empty($val['relation_deep'])) {
  169. $model->getRelation($relationData, $val['relation_deep']);
  170. }
  171. break;
  172. case self::HAS_MANY:
  173. $pk = $result[$mappingKey];
  174. $mappingCondition .= " AND {$mappingFk}='{$pk}'";
  175. $mappingOrder = !empty($val['mapping_order']) ? $val['mapping_order'] : '';
  176. $mappingLimit = !empty($val['mapping_limit']) ? $val['mapping_limit'] : '';
  177. // 延时获取关联记录
  178. $relationData = $model->where($mappingCondition)->field($mappingFields)->order($mappingOrder)->limit($mappingLimit)->select();
  179. if (!empty($val['relation_deep'])) {
  180. foreach ($relationData as $key => $data) {
  181. $model->getRelation($data, $val['relation_deep']);
  182. $relationData[$key] = $data;
  183. }
  184. }
  185. break;
  186. case self::MANY_TO_MANY:
  187. $pk = $result[$mappingKey];
  188. $prefix = $this->tablePrefix;
  189. $mappingCondition = " {$mappingFk}='{$pk}'";
  190. $mappingOrder = $val['mapping_order'];
  191. $mappingLimit = $val['mapping_limit'];
  192. $mappingRelationFk = $val['relation_foreign_key'] ? $val['relation_foreign_key'] : $model->getModelName() . '_id';
  193. if (isset($val['relation_table'])) {
  194. $mappingRelationTable = preg_replace_callback("/__([A-Z_-]+)__/sU", function ($match) use ($prefix) {return $prefix . strtolower($match[1]);}, $val['relation_table']);
  195. } else {
  196. $mappingRelationTable = $this->getRelationTableName($model);
  197. }
  198. $sql = "SELECT b.{$mappingFields} FROM {$mappingRelationTable} AS a, " . $model->getTableName() . " AS b WHERE a.{$mappingRelationFk} = b.{$model->getPk()} AND a.{$mappingCondition}";
  199. if (!empty($val['condition'])) {
  200. $sql .= ' AND ' . $val['condition'];
  201. }
  202. if (!empty($mappingOrder)) {
  203. $sql .= ' ORDER BY ' . $mappingOrder;
  204. }
  205. if (!empty($mappingLimit)) {
  206. $sql .= ' LIMIT ' . $mappingLimit;
  207. }
  208. $relationData = $this->query($sql);
  209. if (!empty($val['relation_deep'])) {
  210. foreach ($relationData as $key => $data) {
  211. $model->getRelation($data, $val['relation_deep']);
  212. $relationData[$key] = $data;
  213. }
  214. }
  215. break;
  216. }
  217. if (!$return) {
  218. if (isset($val['as_fields']) && in_array($mappingType, array(self::HAS_ONE, self::BELONGS_TO))) {
  219. // 支持直接把关联的字段值映射成数据对象中的某个字段
  220. // 仅仅支持HAS_ONE BELONGS_TO
  221. $fields = explode(',', $val['as_fields']);
  222. foreach ($fields as $field) {
  223. if (strpos($field, ':')) {
  224. list($relationName, $nick) = explode(':', $field);
  225. $result[$nick] = $relationData[$relationName];
  226. } else {
  227. $result[$field] = $relationData[$field];
  228. }
  229. }
  230. } else {
  231. $result[$mappingName] = $relationData;
  232. }
  233. unset($relationData);
  234. } else {
  235. return $relationData;
  236. }
  237. }
  238. }
  239. }
  240. return $result;
  241. }
  242. /**
  243. * 操作关联数据
  244. * @access protected
  245. * @param string $opType 操作方式 ADD SAVE DEL
  246. * @param mixed $data 数据对象
  247. * @param string $name 关联名称
  248. * @return mixed
  249. */
  250. protected function opRelation($opType, $data = '', $name = '')
  251. {
  252. $result = false;
  253. if (empty($data) && !empty($this->data)) {
  254. $data = $this->data;
  255. } elseif (!is_array($data)) {
  256. // 数据无效返回
  257. return false;
  258. }
  259. if (!empty($this->_link)) {
  260. // 遍历关联定义
  261. foreach ($this->_link as $key => $val) {
  262. // 操作制定关联类型
  263. $mappingName = $val['mapping_name'] ? $val['mapping_name'] : $key; // 映射名称
  264. if (empty($name) || true === $name || $mappingName == $name || (is_array($name) && in_array($mappingName, $name))) {
  265. // 操作制定的关联
  266. $mappingType = !empty($val['mapping_type']) ? $val['mapping_type'] : $val; // 关联类型
  267. $mappingClass = !empty($val['class_name']) ? $val['class_name'] : $key; // 关联类名
  268. $mappingKey = !empty($val['mapping_key']) ? $val['mapping_key'] : $this->getPk(); // 关联键名
  269. // 当前数据对象主键值
  270. $pk = $data[$mappingKey];
  271. if (strtoupper($mappingClass) == strtoupper($this->name)) {
  272. // 自引用关联 获取父键名
  273. $mappingFk = !empty($val['parent_key']) ? $val['parent_key'] : 'parent_id';
  274. } else {
  275. $mappingFk = !empty($val['foreign_key']) ? $val['foreign_key'] : strtolower($this->name) . '_id'; // 关联外键
  276. }
  277. if (!empty($val['condition'])) {
  278. $mappingCondition = $val['condition'];
  279. } else {
  280. $mappingCondition = array();
  281. $mappingCondition[$mappingFk] = $pk;
  282. }
  283. // 获取关联model对象
  284. $model = D($mappingClass);
  285. $mappingData = isset($data[$mappingName]) ? $data[$mappingName] : false;
  286. if (!empty($mappingData) || 'DEL' == $opType) {
  287. switch ($mappingType) {
  288. case self::HAS_ONE:
  289. switch (strtoupper($opType)) {
  290. case 'ADD': // 增加关联数据
  291. $mappingData[$mappingFk] = $pk;
  292. $result = $model->add($mappingData);
  293. break;
  294. case 'SAVE': // 更新关联数据
  295. $result = $model->where($mappingCondition)->save($mappingData);
  296. break;
  297. case 'DEL': // 根据外键删除关联数据
  298. $result = $model->where($mappingCondition)->delete();
  299. break;
  300. }
  301. break;
  302. case self::BELONGS_TO:
  303. break;
  304. case self::HAS_MANY:
  305. switch (strtoupper($opType)) {
  306. case 'ADD': // 增加关联数据
  307. $model->startTrans();
  308. foreach ($mappingData as $val) {
  309. $val[$mappingFk] = $pk;
  310. $result = $model->add($val);
  311. }
  312. $model->commit();
  313. break;
  314. case 'SAVE': // 更新关联数据
  315. $model->startTrans();
  316. $pk = $model->getPk();
  317. foreach ($mappingData as $vo) {
  318. if (isset($vo[$pk])) {
  319. // 更新数据
  320. $mappingCondition = "$pk ={$vo[$pk]}";
  321. $result = $model->where($mappingCondition)->save($vo);
  322. } else {
  323. // 新增数据
  324. $vo[$mappingFk] = $data[$mappingKey];
  325. $result = $model->add($vo);
  326. }
  327. }
  328. $model->commit();
  329. break;
  330. case 'DEL': // 删除关联数据
  331. $result = $model->where($mappingCondition)->delete();
  332. break;
  333. }
  334. break;
  335. case self::MANY_TO_MANY:
  336. $mappingRelationFk = $val['relation_foreign_key'] ? $val['relation_foreign_key'] : $model->getModelName() . '_id'; // 关联
  337. $prefix = $this->tablePrefix;
  338. if (isset($val['relation_table'])) {
  339. $mappingRelationTable = preg_replace_callback("/__([A-Z_-]+)__/sU", function ($match) use ($prefix) {return $prefix . strtolower($match[1]);}, $val['relation_table']);
  340. } else {
  341. $mappingRelationTable = $this->getRelationTableName($model);
  342. }
  343. if (is_array($mappingData)) {
  344. $ids = array();
  345. foreach ($mappingData as $vo) {
  346. $ids[] = $vo[$mappingKey];
  347. }
  348. $relationId = implode(',', $ids);
  349. }
  350. switch (strtoupper($opType)) {
  351. case 'ADD': // 增加关联数据
  352. if (isset($relationId)) {
  353. $this->startTrans();
  354. // 插入关联表数据
  355. $sql = 'INSERT INTO ' . $mappingRelationTable . ' (' . $mappingFk . ',' . $mappingRelationFk . ') SELECT a.' . $this->getPk() . ',b.' . $model->getPk() . ' FROM ' . $this->getTableName() . ' AS a ,' . $model->getTableName() . " AS b where a." . $this->getPk() . ' =' . $pk . ' AND b.' . $model->getPk() . ' IN (' . $relationId . ") ";
  356. $result = $model->execute($sql);
  357. if (false !== $result)
  358. // 提交事务
  359. {
  360. $this->commit();
  361. } else
  362. // 事务回滚
  363. {
  364. $this->rollback();
  365. }
  366. }
  367. break;
  368. case 'SAVE': // 更新关联数据
  369. if (isset($relationId)) {
  370. $this->startTrans();
  371. // 删除关联表数据
  372. $this->table($mappingRelationTable)->where($mappingCondition)->delete();
  373. // 插入关联表数据
  374. $sql = 'INSERT INTO ' . $mappingRelationTable . ' (' . $mappingFk . ',' . $mappingRelationFk . ') SELECT a.' . $this->getPk() . ',b.' . $model->getPk() . ' FROM ' . $this->getTableName() . ' AS a ,' . $model->getTableName() . " AS b where a." . $this->getPk() . ' =' . $pk . ' AND b.' . $model->getPk() . ' IN (' . $relationId . ") ";
  375. $result = $model->execute($sql);
  376. if (false !== $result)
  377. // 提交事务
  378. {
  379. $this->commit();
  380. } else
  381. // 事务回滚
  382. {
  383. $this->rollback();
  384. }
  385. }
  386. break;
  387. case 'DEL': // 根据外键删除中间表关联数据
  388. $result = $this->table($mappingRelationTable)->where($mappingCondition)->delete();
  389. break;
  390. }
  391. break;
  392. }
  393. if (!empty($val['relation_deep'])) {
  394. $model->opRelation($opType, $mappingData, $val['relation_deep']);
  395. }
  396. }
  397. }
  398. }
  399. }
  400. return $result;
  401. }
  402. /**
  403. * 进行关联查询
  404. * @access public
  405. * @param mixed $name 关联名称
  406. * @return Model
  407. */
  408. public function relation($name)
  409. {
  410. $this->options['link'] = $name;
  411. return $this;
  412. }
  413. /**
  414. * 关联数据获取 仅用于查询后
  415. * @access public
  416. * @param string $name 关联名称
  417. * @return array
  418. */
  419. public function relationGet($name)
  420. {
  421. if (empty($this->data)) {
  422. return false;
  423. }
  424. return $this->getRelation($this->data, $name, true);
  425. }
  426. }