MergeModel.class.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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 MergeModel extends Model
  17. {
  18. protected $modelList = array(); // 包含的模型列表 第一个必须是主表模型
  19. protected $masterModel = ''; // 主模型
  20. protected $joinType = 'INNER'; // 聚合模型的查询JOIN类型
  21. protected $fk = ''; // 外键名 默认为主表名_id
  22. protected $mapFields = array(); // 需要处理的模型映射字段,避免混淆 array( id => 'user.id' )
  23. /**
  24. * 架构函数
  25. * 取得DB类的实例对象 字段检查
  26. * @access public
  27. * @param string $name 模型名称
  28. * @param string $tablePrefix 表前缀
  29. * @param mixed $connection 数据库连接信息
  30. */
  31. public function __construct($name = '', $tablePrefix = '', $connection = '')
  32. {
  33. parent::__construct($name, $tablePrefix, $connection);
  34. // 聚合模型的字段信息
  35. if (empty($this->fields) && !empty($this->modelList)) {
  36. $fields = array();
  37. foreach ($this->modelList as $model) {
  38. // 获取模型的字段信息
  39. $result = $this->db->getFields(M($model)->getTableName());
  40. $_fields = array_keys($result);
  41. // $this->mapFields = array_intersect($fields,$_fields);
  42. $fields = array_merge($fields, $_fields);
  43. }
  44. $this->fields = $fields;
  45. }
  46. // 设置第一个模型为主表模型
  47. if (empty($this->masterModel) && !empty($this->modelList)) {
  48. $this->masterModel = $this->modelList[0];
  49. }
  50. // 主表的主键名
  51. $this->pk = M($this->masterModel)->getPk();
  52. // 设置默认外键名 仅支持单一外键
  53. if (empty($this->fk)) {
  54. $this->fk = strtolower($this->masterModel) . '_id';
  55. }
  56. }
  57. /**
  58. * 得到完整的数据表名
  59. * @access public
  60. * @return string
  61. */
  62. public function getTableName()
  63. {
  64. if (empty($this->trueTableName)) {
  65. $tableName = array();
  66. $models = $this->modelList;
  67. foreach ($models as $model) {
  68. $tableName[] = M($model)->getTableName() . ' ' . $model;
  69. }
  70. $this->trueTableName = implode(',', $tableName);
  71. }
  72. return $this->trueTableName;
  73. }
  74. /**
  75. * 自动检测数据表信息
  76. * @access protected
  77. * @return void
  78. */
  79. protected function _checkTableInfo()
  80. {}
  81. /**
  82. * 新增聚合数据
  83. * @access public
  84. * @param mixed $data 数据
  85. * @param array $options 表达式
  86. * @param boolean $replace 是否replace
  87. * @return mixed
  88. */
  89. public function add($data = '', $options = array(), $replace = false)
  90. {
  91. if (empty($data)) {
  92. // 没有传递数据,获取当前数据对象的值
  93. if (!empty($this->data)) {
  94. $data = $this->data;
  95. // 重置数据
  96. $this->data = array();
  97. } else {
  98. $this->error = L('_DATA_TYPE_INVALID_');
  99. return false;
  100. }
  101. }
  102. // 启动事务
  103. $this->startTrans();
  104. // 写入主表数据
  105. $result = M($this->masterModel)->strict(false)->add($data);
  106. if ($result) {
  107. // 写入外键数据
  108. $data[$this->fk] = $result;
  109. $models = $this->modelList;
  110. array_shift($models);
  111. // 写入附表数据
  112. foreach ($models as $model) {
  113. $res = M($model)->strict(false)->add($data);
  114. if (!$res) {
  115. $this->rollback();
  116. return false;
  117. }
  118. }
  119. // 提交事务
  120. $this->commit();
  121. } else {
  122. $this->rollback();
  123. return false;
  124. }
  125. return $result;
  126. }
  127. /**
  128. * 对保存到数据库的数据进行处理
  129. * @access protected
  130. * @param mixed $data 要操作的数据
  131. * @return boolean
  132. */
  133. protected function _facade($data)
  134. {
  135. // 检查数据字段合法性
  136. if (!empty($this->fields)) {
  137. if (!empty($this->options['field'])) {
  138. $fields = $this->options['field'];
  139. unset($this->options['field']);
  140. if (is_string($fields)) {
  141. $fields = explode(',', $fields);
  142. }
  143. } else {
  144. $fields = $this->fields;
  145. }
  146. foreach ($data as $key => $val) {
  147. if (!in_array($key, $fields, true)) {
  148. unset($data[$key]);
  149. } elseif (array_key_exists($key, $this->mapFields)) {
  150. // 需要处理映射字段
  151. $data[$this->mapFields[$key]] = $val;
  152. unset($data[$key]);
  153. }
  154. }
  155. }
  156. // 安全过滤
  157. if (!empty($this->options['filter'])) {
  158. $data = array_map($this->options['filter'], $data);
  159. unset($this->options['filter']);
  160. }
  161. $this->_before_write($data);
  162. return $data;
  163. }
  164. /**
  165. * 保存聚合模型数据
  166. * @access public
  167. * @param mixed $data 数据
  168. * @param array $options 表达式
  169. * @return boolean
  170. */
  171. public function save($data = '', $options = array())
  172. {
  173. // 根据主表的主键更新
  174. if (empty($data)) {
  175. // 没有传递数据,获取当前数据对象的值
  176. if (!empty($this->data)) {
  177. $data = $this->data;
  178. // 重置数据
  179. $this->data = array();
  180. } else {
  181. $this->error = L('_DATA_TYPE_INVALID_');
  182. return false;
  183. }
  184. }
  185. if (empty($data)) {
  186. // 没有数据则不执行
  187. $this->error = L('_DATA_TYPE_INVALID_');
  188. return false;
  189. }
  190. // 如果存在主键数据 则自动作为更新条件
  191. $pk = $this->pk;
  192. if (isset($data[$pk])) {
  193. $where[$pk] = $data[$pk];
  194. $options['where'] = $where;
  195. unset($data[$pk]);
  196. }
  197. $options['join'] = '';
  198. $options = $this->_parseOptions($options);
  199. // 更新操作不使用JOIN
  200. $options['table'] = $this->getTableName();
  201. if (is_array($options['where']) && isset($options['where'][$pk])) {
  202. $pkValue = $options['where'][$pk];
  203. }
  204. if (false === $this->_before_update($data, $options)) {
  205. return false;
  206. }
  207. $result = $this->db->update($data, $options);
  208. if (false !== $result) {
  209. if (isset($pkValue)) {
  210. $data[$pk] = $pkValue;
  211. }
  212. $this->_after_update($data, $options);
  213. }
  214. return $result;
  215. }
  216. /**
  217. * 删除聚合模型数据
  218. * @access public
  219. * @param mixed $options 表达式
  220. * @return mixed
  221. */
  222. public function delete($options = array())
  223. {
  224. $pk = $this->pk;
  225. if (empty($options) && empty($this->options['where'])) {
  226. // 如果删除条件为空 则删除当前数据对象所对应的记录
  227. if (!empty($this->data) && isset($this->data[$pk])) {
  228. return $this->delete($this->data[$pk]);
  229. } else {
  230. return false;
  231. }
  232. }
  233. if (is_numeric($options) || is_string($options)) {
  234. // 根据主键删除记录
  235. if (strpos($options, ',')) {
  236. $where[$pk] = array('IN', $options);
  237. } else {
  238. $where[$pk] = $options;
  239. }
  240. $options = array();
  241. $options['where'] = $where;
  242. }
  243. // 分析表达式
  244. $options['join'] = '';
  245. $options = $this->_parseOptions($options);
  246. if (empty($options['where'])) {
  247. // 如果条件为空 不进行删除操作 除非设置 1=1
  248. return false;
  249. }
  250. if (is_array($options['where']) && isset($options['where'][$pk])) {
  251. $pkValue = $options['where'][$pk];
  252. }
  253. $options['table'] = implode(',', $this->modelList);
  254. $options['using'] = $this->getTableName();
  255. if (false === $this->_before_delete($options)) {
  256. return false;
  257. }
  258. $result = $this->db->delete($options);
  259. if (false !== $result) {
  260. $data = array();
  261. if (isset($pkValue)) {
  262. $data[$pk] = $pkValue;
  263. }
  264. $this->_after_delete($data, $options);
  265. }
  266. // 返回删除记录个数
  267. return $result;
  268. }
  269. /**
  270. * 表达式过滤方法
  271. * @access protected
  272. * @param string $options 表达式
  273. * @return void
  274. */
  275. protected function _options_filter(&$options)
  276. {
  277. if (!isset($options['join'])) {
  278. $models = $this->modelList;
  279. array_shift($models);
  280. foreach ($models as $model) {
  281. $options['join'][] = $this->joinType . ' JOIN ' . M($model)->getTableName() . ' ' . $model . ' ON ' . $this->masterModel . '.' . $this->pk . ' = ' . $model . '.' . $this->fk;
  282. }
  283. }
  284. $options['table'] = M($this->masterModel)->getTableName() . ' ' . $this->masterModel;
  285. $options['field'] = $this->checkFields(isset($options['field']) ? $options['field'] : '');
  286. if (isset($options['group'])) {
  287. $options['group'] = $this->checkGroup($options['group']);
  288. }
  289. if (isset($options['where'])) {
  290. $options['where'] = $this->checkCondition($options['where']);
  291. }
  292. if (isset($options['order'])) {
  293. $options['order'] = $this->checkOrder($options['order']);
  294. }
  295. }
  296. /**
  297. * 检查条件中的聚合字段
  298. * @access protected
  299. * @param mixed $data 条件表达式
  300. * @return array
  301. */
  302. protected function checkCondition($where)
  303. {
  304. if (is_array($where)) {
  305. $view = array();
  306. foreach ($where as $name => $value) {
  307. if (array_key_exists($name, $this->mapFields)) {
  308. // 需要处理映射字段
  309. $view[$this->mapFields[$name]] = $value;
  310. unset($where[$name]);
  311. }
  312. }
  313. $where = array_merge($where, $view);
  314. }
  315. return $where;
  316. }
  317. /**
  318. * 检查Order表达式中的聚合字段
  319. * @access protected
  320. * @param string $order 字段
  321. * @return string
  322. */
  323. protected function checkOrder($order = '')
  324. {
  325. if (is_string($order) && !empty($order)) {
  326. $orders = explode(',', $order);
  327. $_order = array();
  328. foreach ($orders as $order) {
  329. $array = explode(' ', trim($order));
  330. $field = $array[0];
  331. $sort = isset($array[1]) ? $array[1] : 'ASC';
  332. if (array_key_exists($field, $this->mapFields)) {
  333. // 需要处理映射字段
  334. $field = $this->mapFields[$field];
  335. }
  336. $_order[] = $field . ' ' . $sort;
  337. }
  338. $order = implode(',', $_order);
  339. }
  340. return $order;
  341. }
  342. /**
  343. * 检查Group表达式中的聚合字段
  344. * @access protected
  345. * @param string $group 字段
  346. * @return string
  347. */
  348. protected function checkGroup($group = '')
  349. {
  350. if (!empty($group)) {
  351. $groups = explode(',', $group);
  352. $_group = array();
  353. foreach ($groups as $field) {
  354. // 解析成聚合字段
  355. if (array_key_exists($field, $this->mapFields)) {
  356. // 需要处理映射字段
  357. $field = $this->mapFields[$field];
  358. }
  359. $_group[] = $field;
  360. }
  361. $group = implode(',', $_group);
  362. }
  363. return $group;
  364. }
  365. /**
  366. * 检查fields表达式中的聚合字段
  367. * @access protected
  368. * @param string $fields 字段
  369. * @return string
  370. */
  371. protected function checkFields($fields = '')
  372. {
  373. if (empty($fields) || '*' == $fields) {
  374. // 获取全部聚合字段
  375. $fields = $this->fields;
  376. }
  377. if (!is_array($fields)) {
  378. $fields = explode(',', $fields);
  379. }
  380. // 解析成聚合字段
  381. $array = array();
  382. foreach ($fields as $field) {
  383. if (array_key_exists($field, $this->mapFields)) {
  384. // 需要处理映射字段
  385. $array[] = $this->mapFields[$field] . ' AS ' . $field;
  386. } else {
  387. $array[] = $field;
  388. }
  389. }
  390. $fields = implode(',', $array);
  391. return $fields;
  392. }
  393. /**
  394. * 获取数据表字段信息
  395. * @access public
  396. * @return array
  397. */
  398. public function getDbFields()
  399. {
  400. return $this->fields;
  401. }
  402. }