You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

323 lines
11 KiB

  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;
  12. use think\Db;
  13. use think\db\Query;
  14. use think\Model;
  15. class Merge extends Model
  16. {
  17. protected $relationModel = []; // HAS ONE 关联的模型列表
  18. protected $fk = ''; // 外键名 默认为主表名_id
  19. protected $mapFields = []; // 需要处理的模型映射字段,避免混淆 array( id => 'user.id' )
  20. /**
  21. * 构造函数
  22. * @access public
  23. * @param array|object $data 数据
  24. */
  25. public function __construct($data = [])
  26. {
  27. parent::__construct($data);
  28. // 设置默认外键名 仅支持单一外键
  29. if (empty($this->fk)) {
  30. $this->fk = strtolower($this->name) . '_id';
  31. }
  32. }
  33. /**
  34. * 查找单条记录
  35. * @access public
  36. * @param mixed $data 主键值或者查询条件(闭包)
  37. * @param string|array $with 关联预查询
  38. * @param bool $cache 是否缓存
  39. * @return \think\Model
  40. */
  41. public static function get($data = null, $with = [], $cache = false)
  42. {
  43. $query = self::parseQuery($data, $with, $cache);
  44. $query = self::attachQuery($query);
  45. return $query->find($data);
  46. }
  47. /**
  48. * 附加查询表达式
  49. * @access protected
  50. * @param \think\db\Query $query 查询对象
  51. * @return \think\db\Query
  52. */
  53. protected static function attachQuery($query)
  54. {
  55. $class = new static();
  56. $master = $class->name;
  57. $fields = self::getModelField($query, $master, '', $class->mapFields, $class->field);
  58. $query->alias($master)->field($fields);
  59. foreach ($class->relationModel as $key => $model) {
  60. $name = is_int($key) ? $model : $key;
  61. $table = is_int($key) ? $query->getTable($name) : $model;
  62. $query->join($table . ' ' . $name, $name . '.' . $class->fk . '=' . $master . '.' . $class->getPk());
  63. $fields = self::getModelField($query, $name, $table, $class->mapFields, $class->field);
  64. $query->field($fields);
  65. }
  66. return $query;
  67. }
  68. /**
  69. * 获取关联模型的字段 并解决混淆
  70. * @access protected
  71. * @param \think\db\Query $query 查询对象
  72. * @param string $name 模型名称
  73. * @param string $table 关联表名称
  74. * @param array $map 字段映射
  75. * @param array $fields 查询字段
  76. * @return array
  77. */
  78. protected static function getModelField($query, $name, $table = '', $map = [], $fields = [])
  79. {
  80. // 获取模型的字段信息
  81. $fields = $fields ?: $query->getTableInfo($table, 'fields');
  82. $array = [];
  83. foreach ($fields as $field) {
  84. if ($key = array_search($name . '.' . $field, $map)) {
  85. // 需要处理映射字段
  86. $array[] = $name . '.' . $field . ' AS ' . $key;
  87. } else {
  88. $array[] = $field;
  89. }
  90. }
  91. return $array;
  92. }
  93. /**
  94. * 查找所有记录
  95. * @access public
  96. * @param mixed $data 主键列表或者查询条件(闭包)
  97. * @param array|string $with 关联预查询
  98. * @param bool $cache
  99. * @return array|false|string
  100. */
  101. public static function all($data = null, $with = [], $cache = false)
  102. {
  103. $query = self::parseQuery($data, $with, $cache);
  104. $query = self::attachQuery($query);
  105. return $query->select($data);
  106. }
  107. /**
  108. * 处理写入的模型数据
  109. * @access public
  110. * @param string $model 模型名称
  111. * @param array $data 数据
  112. * @return array
  113. */
  114. protected function parseData($model, $data)
  115. {
  116. $item = [];
  117. foreach ($data as $key => $val) {
  118. if ($this->fk != $key && array_key_exists($key, $this->mapFields)) {
  119. list($name, $key) = explode('.', $this->mapFields[$key]);
  120. if ($model == $name) {
  121. $item[$key] = $val;
  122. }
  123. } else {
  124. $item[$key] = $val;
  125. }
  126. }
  127. return $item;
  128. }
  129. /**
  130. * 保存模型数据 以及关联数据
  131. * @access public
  132. * @param mixed $data 数据
  133. * @param array $where 更新条件
  134. * @param string $sequence 自增序列名
  135. * @return false|int
  136. * @throws \Exception
  137. */
  138. public function save($data = [], $where = [], $sequence = null)
  139. {
  140. if (!empty($data)) {
  141. // 数据自动验证
  142. if (!$this->validateData($data)) {
  143. return false;
  144. }
  145. // 数据对象赋值
  146. foreach ($data as $key => $value) {
  147. $this->setAttr($key, $value, $data);
  148. }
  149. if (!empty($where)) {
  150. $this->isUpdate = true;
  151. }
  152. }
  153. // 数据自动完成
  154. $this->autoCompleteData($this->auto);
  155. // 自动写入更新时间
  156. if ($this->autoWriteTimestamp && $this->updateTime && !isset($this->data[$this->updateTime])) {
  157. $this->setAttr($this->updateTime, null);
  158. }
  159. // 事件回调
  160. if (false === $this->trigger('before_write', $this)) {
  161. return false;
  162. }
  163. $db = $this->db();
  164. $db->startTrans();
  165. $pk = $this->getPk();
  166. try {
  167. if ($this->isUpdate) {
  168. // 自动写入
  169. $this->autoCompleteData($this->update);
  170. if (false === $this->trigger('before_update', $this)) {
  171. return false;
  172. }
  173. if (empty($where) && !empty($this->updateWhere)) {
  174. $where = $this->updateWhere;
  175. }
  176. // 获取有更新的数据
  177. $data = $this->getChangedData();
  178. // 保留主键数据
  179. foreach ($this->data as $key => $val) {
  180. if ($this->isPk($key)) {
  181. $data[$key] = $val;
  182. }
  183. }
  184. // 处理模型数据
  185. $data = $this->parseData($this->name, $data);
  186. if (is_string($pk) && isset($data[$pk])) {
  187. if (!isset($where[$pk])) {
  188. unset($where);
  189. $where[$pk] = $data[$pk];
  190. }
  191. unset($data[$pk]);
  192. }
  193. // 写入主表数据
  194. $result = $db->strict(false)->where($where)->update($data);
  195. // 写入附表数据
  196. foreach ($this->relationModel as $key => $model) {
  197. $name = is_int($key) ? $model : $key;
  198. $table = is_int($key) ? $db->getTable($model) : $model;
  199. // 处理关联模型数据
  200. $data = $this->parseData($name, $data);
  201. if (Db::table($table)->strict(false)->where($this->fk, $this->data[$this->getPk()])->update($data)) {
  202. $result = 1;
  203. }
  204. }
  205. // 新增回调
  206. $this->trigger('after_update', $this);
  207. } else {
  208. // 自动写入
  209. $this->autoCompleteData($this->insert);
  210. // 自动写入创建时间
  211. if ($this->autoWriteTimestamp && $this->createTime && !isset($this->data[$this->createTime])) {
  212. $this->setAttr($this->createTime, null);
  213. }
  214. if (false === $this->trigger('before_insert', $this)) {
  215. return false;
  216. }
  217. // 处理模型数据
  218. $data = $this->parseData($this->name, $this->data);
  219. // 写入主表数据
  220. $result = $db->name($this->name)->strict(false)->insert($data);
  221. if ($result) {
  222. $insertId = $db->getLastInsID($sequence);
  223. // 写入外键数据
  224. if ($insertId) {
  225. if (is_string($pk)) {
  226. $this->data[$pk] = $insertId;
  227. }
  228. $this->data[$this->fk] = $insertId;
  229. }
  230. // 写入附表数据
  231. $source = $this->data;
  232. if ($insertId && is_string($pk) && isset($source[$pk]) && $this->fk != $pk) {
  233. unset($source[$pk]);
  234. }
  235. foreach ($this->relationModel as $key => $model) {
  236. $name = is_int($key) ? $model : $key;
  237. $table = is_int($key) ? $db->getTable($model) : $model;
  238. // 处理关联模型数据
  239. $data = $this->parseData($name, $source);
  240. Db::table($table)->strict(false)->insert($data);
  241. }
  242. }
  243. // 标记为更新
  244. $this->isUpdate = true;
  245. // 新增回调
  246. $this->trigger('after_insert', $this);
  247. }
  248. $db->commit();
  249. // 写入回调
  250. $this->trigger('after_write', $this);
  251. $this->origin = $this->data;
  252. return $result;
  253. } catch (\Exception $e) {
  254. $db->rollback();
  255. throw $e;
  256. }
  257. }
  258. /**
  259. * 删除当前的记录 并删除关联数据
  260. * @access public
  261. * @return int
  262. * @throws \Exception
  263. */
  264. public function delete()
  265. {
  266. if (false === $this->trigger('before_delete', $this)) {
  267. return false;
  268. }
  269. $db = $this->db();
  270. $db->startTrans();
  271. try {
  272. $result = $db->delete($this->data);
  273. if ($result) {
  274. // 获取主键数据
  275. $pk = $this->data[$this->getPk()];
  276. // 删除关联数据
  277. foreach ($this->relationModel as $key => $model) {
  278. $table = is_int($key) ? $db->getTable($model) : $model;
  279. $query = new Query;
  280. $query->table($table)->where($this->fk, $pk)->delete();
  281. }
  282. }
  283. $this->trigger('after_delete', $this);
  284. $db->commit();
  285. return $result;
  286. } catch (\Exception $e) {
  287. $db->rollback();
  288. throw $e;
  289. }
  290. }
  291. }