RelationModel.class.php 22 KB

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