table.class.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. <?php
  2. /**
  3. * [WeEngine System] Copyright (c) 2014 WE7.CC
  4. * WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details.
  5. */
  6. defined('IN_IA') or exit('Access Denied');
  7. abstract class We7Table {
  8. const ONE_TO_ONE = 'ONE_TO_ONE';
  9. const ONE_TO_MANY = 'ONE_TO_MANY';
  10. const BELONGS_TO = 'BELONGS_TO';
  11. const MANY_TO_MANY = 'MANY_TO_MANY';
  12. protected $tableName = '';
  13. protected $primaryKey = 'id';
  14. protected $field = array('group_id');
  15. protected $rule = array();
  16. protected $default = array();
  17. protected $cast = array();
  18. protected $query;
  19. private $attribute = array();
  20. private $relationDefine = array();
  21. public function __construct() {
  22. load()->classs('validator');
  23. $this->query = load()->object('Query');
  24. $this->query->fixTable = $this->tableName;
  25. $this->query->from($this->tableName);
  26. }
  27. public function searchWithPage($pageindex, $pagesize) {
  28. if (!empty($pageindex) && !empty($pagesize)) {
  29. $this->query->page($pageindex, $pagesize);
  30. }
  31. return $this;
  32. }
  33. public function getLastQueryTotal() {
  34. return $this->query->getLastQueryTotal();
  35. }
  36. public function count() {
  37. return $this->query->count();
  38. }
  39. public function fill($field, $value = '') {
  40. if (is_array($field)) {
  41. foreach ($field as $column => $val) {
  42. $this->fillField($column, $val);
  43. }
  44. return $this;
  45. }
  46. $this->fillField($field, $value);
  47. return $this;
  48. }
  49. private function fillField($column, $val) {
  50. if (in_array($column, $this->field)) {
  51. $val = $this->getColumnVal($column, $val);
  52. $this->attribute[$column] = $val;
  53. $this->query->fill($column, $val);
  54. }
  55. }
  56. private function getColumnVal($column, $val) {
  57. $method = 'set' . $this->studly($column) . 'Field';
  58. if (method_exists($this, $method)) {
  59. return $this->{$method}($val);
  60. }
  61. return $this->cast($column, $val);
  62. }
  63. private function cast($column, $val) {
  64. if (isset($this->cast[$column])) {
  65. switch ($this->cast[$column]) {
  66. case 'int': return intval($val); break;
  67. case 'string': return strval($val); break;
  68. case 'float': return floatval($val); break;
  69. case 'double': return doubleval($val); break;
  70. case 'bool': return boolval($val); break;
  71. }
  72. }
  73. return $val;
  74. }
  75. private function appendDefault() {
  76. foreach ($this->default as $field => $value) {
  77. if (!isset($this->attribute[$field])) {
  78. if ('custom' === $value) {
  79. $method = 'default' . $this->studly($field);
  80. if (!method_exists($this, $method)) {
  81. trigger_error($method . '方法未找到');
  82. }
  83. $value = call_user_func(array($this, $method));
  84. }
  85. $this->fillField($field, $value);
  86. }
  87. }
  88. }
  89. protected function valid($data) {
  90. if (count($this->rule) <= 0) {
  91. return error(0);
  92. }
  93. $validator = Validator::create($data, $this->rule);
  94. $result = $validator->valid();
  95. return $result;
  96. }
  97. public function select($fields = '*') {
  98. return $this->query->select($fields);
  99. }
  100. public function limit($limit) {
  101. return $this->query->limit($limit);
  102. }
  103. public function get() {
  104. $data = $this->query->get();
  105. if (!$data || empty($data)) {
  106. return $data;
  107. }
  108. $this->loadRelation($data);
  109. return $data;
  110. }
  111. public function getall($keyfield = '') {
  112. $data = $this->query->getall($keyfield);
  113. if (!$data || empty($data)) {
  114. return $data;
  115. }
  116. $this->loadRelation($data, true);
  117. return $data;
  118. }
  119. public function getQuery() {
  120. return $this->query;
  121. }
  122. public function getTableName() {
  123. return $this->tableName;
  124. }
  125. public function with($relation) {
  126. $relations = is_string($relation) ? func_get_args() : $relation;
  127. foreach ($relations as $relation => $val) {
  128. if (is_numeric($relation)) {
  129. $relation = $val;
  130. }
  131. if (!is_callable($val)) {
  132. $val = null;
  133. }
  134. $this->relationDefine[$relation] = $val;
  135. }
  136. return $this;
  137. }
  138. private function loadRelation(array &$data, $muti = false) {
  139. foreach ($this->relationDefine as $relation => $closure) {
  140. $this->doload($relation, $data, $muti, $closure);
  141. }
  142. }
  143. private function doload($relation, &$data, $muti = false, callable $closure = null) {
  144. if (method_exists($this, $relation)) {
  145. $relation_param = call_user_func(array($this, $relation));
  146. list($type, $table, $foreign_key, $owner_key) = $relation_param;
  147. if (self::MANY_TO_MANY == $type) {
  148. $this->doManyToMany($relation, $relation_param, $data, $muti);
  149. return;
  150. }
  151. $single = $this->isGetSingle($type);
  152. $foreign_vals = $this->getForeignVal($data, $owner_key, $muti);
  153. $second_table_data = $this->getSecondTableData($table, $foreign_key, $foreign_vals, $single, $closure);
  154. if (!$muti) {
  155. $data[$relation] = $second_table_data;
  156. return;
  157. }
  158. if ($single) {
  159. $second_table_data = array($second_table_data);
  160. }
  161. $second_table_data = $this->groupBy($foreign_key, $second_table_data);
  162. foreach ($data as &$item) {
  163. $relation_val = isset($second_table_data[$item[$owner_key]]) ? $second_table_data[$item[$owner_key]] : array();
  164. if ($single) {
  165. $relation_val = count($relation_val) > 0 ? current($relation_val) : array();
  166. }
  167. $item[$relation] = $relation_val;
  168. }
  169. }
  170. }
  171. private function doManyToMany($relation, $relation_param, &$data, $muti = false) {
  172. list($type, $table, $foreign_key, $owner_key, $center_table, $center_foreign_key, $center_owner_key)
  173. = $relation_param;
  174. $foreign_vals = $this->getForeignVal($data, $owner_key, $muti);
  175. $three_table = table($table);
  176. $nativeQuery = $three_table->getQuery();
  177. $nativeQuery->from($three_table->getTableName(), 'three')
  178. ->innerjoin($center_table, 'center')
  179. ->on(array('center.' . $center_foreign_key => 'three.' . $foreign_key))
  180. ->select('center.*')
  181. ->where('center.' . $center_owner_key, $foreign_vals);
  182. $three_table_data = $three_table->getall();
  183. if (!$muti) {
  184. $data[$relation] = $three_table_data;
  185. return;
  186. }
  187. $three_table_data = $this->groupBy($center_owner_key, $three_table_data);
  188. foreach ($data as &$item) {
  189. $three_val = isset($three_table_data[$item[$owner_key]]) ? $three_table_data[$item[$owner_key]] : array();
  190. $item[$relation] = $three_val;
  191. }
  192. }
  193. private function isGetSingle($type) {
  194. return in_array($type, array(self::ONE_TO_ONE, self::BELONGS_TO)) ? true : false;
  195. }
  196. private function getForeignVal($data, $owner_key, $muti = false) {
  197. if (!$muti) {
  198. return $data[$owner_key];
  199. }
  200. return array_map(function ($item) use ($owner_key) {
  201. return $item[$owner_key];
  202. }, $data);
  203. }
  204. private function getSecondTableData($table, $foreign_key, $foreign_vals, $single = false, $closure = null) {
  205. $table_instance = table($table)->where($foreign_key, $foreign_vals);
  206. if ($closure) {
  207. call_user_func($closure, $table_instance->getQuery());
  208. }
  209. if ($single) {
  210. return $table_instance->get();
  211. }
  212. return $table_instance->getall();
  213. }
  214. private function groupBy($key, $array) {
  215. $result = array();
  216. foreach ($array as $item) {
  217. $val = $item[$key];
  218. if (isset($result[$val])) {
  219. $result[$val][] = $item;
  220. } else {
  221. $result[$val] = array($item);
  222. }
  223. }
  224. return $result;
  225. }
  226. protected function hasOne($table, $foreign_key, $owner_key = false) {
  227. return $this->relationArray(self::ONE_TO_ONE, $table, $foreign_key, $owner_key);
  228. }
  229. protected function hasMany($table, $foreign_key, $owner_key = false) {
  230. return $this->relationArray(self::ONE_TO_MANY, $table, $foreign_key, $owner_key);
  231. }
  232. protected function belongsTo($table, $foreign_key, $owner_key = false) {
  233. return $this->relationArray(self::BELONGS_TO, $table, $foreign_key, $owner_key);
  234. }
  235. protected function belongsMany($table, $foreign_key, $owner_key, $center_table, $center_foreign_key = false,
  236. $center_owner_key = false) {
  237. if (!$owner_key) {
  238. $owner_key = $this->primaryKey;
  239. }
  240. if (!$center_foreign_key) {
  241. $center_foreign_key = $foreign_key;
  242. }
  243. if (!$center_owner_key) {
  244. $center_owner_key = $owner_key;
  245. }
  246. return array(self::MANY_TO_MANY, $table, $foreign_key, $owner_key, $center_table, $center_foreign_key, $center_owner_key);
  247. }
  248. private function relationArray($type, $table, $foreign_key, $owner_key) {
  249. if (!$owner_key) {
  250. $owner_key = $this->primaryKey;
  251. }
  252. if (!in_array($type, array(self::ONE_TO_ONE, self::ONE_TO_MANY, self::BELONGS_TO), true)) {
  253. trigger_error('不支持的关联类型');
  254. }
  255. return array($type, $table, $foreign_key, $owner_key);
  256. }
  257. public function getById($id, $uniacid = 0) {
  258. $this->query->from($this->tableName)->where($this->primaryKey, $id);
  259. if (!empty($uniacid)) {
  260. $this->where('uniacid', $uniacid);
  261. }
  262. if (is_array($id)) {
  263. return $this->getall();
  264. }
  265. return $this->get();
  266. }
  267. public function getcolumn($field = '') {
  268. $data = $this->query->getcolumn($field);
  269. return $data;
  270. }
  271. public function where($condition, $parameters = array(), $operator = 'AND') {
  272. $this->query->where($condition, $parameters, $operator);
  273. return $this;
  274. }
  275. public function whereor($condition, $parameters = array()) {
  276. return $this->where($condition, $parameters, 'OR');
  277. }
  278. public function orderby($field, $direction = 'ASC') {
  279. return $this->query->orderby($field, $direction);
  280. }
  281. public function save($replace = false) {
  282. if ($this->query->hasWhere()) {
  283. $result = $this->valid($this->attribute);
  284. if (is_error($result)) {
  285. return $result;
  286. }
  287. return $this->query->update();
  288. }
  289. $this->appendDefault();
  290. $result = $this->valid($this->attribute);
  291. if (is_error($result)) {
  292. return $result;
  293. }
  294. return $this->query->insert($replace);
  295. }
  296. public function delete() {
  297. if ($this->query->hasWhere()) {
  298. return $this->query->delete();
  299. }
  300. return false;
  301. }
  302. private function doWhere($field, $params, $operator = 'AND') {
  303. if (0 == $params) {
  304. return $this;
  305. }
  306. $value = $params[0];
  307. if (count($params) > 1) {
  308. $field = $field . ' ' . $params[1];
  309. }
  310. $this->query->where($field, $value, $operator);
  311. return $this;
  312. }
  313. private function snake($value) {
  314. $delimiter = '_';
  315. if (!ctype_lower($value)) {
  316. $value = preg_replace('/\s+/u', '', ucwords($value));
  317. $value = strtolower(preg_replace('/(.)(?=[A-Z])/u', '$1' . $delimiter, $value));
  318. }
  319. return $value;
  320. }
  321. private function studly($value) {
  322. $value = ucwords(str_replace(array('-', '_'), ' ', $value));
  323. return str_replace(' ', '', $value);
  324. }
  325. public function __call($method, $params) {
  326. $actions = array(
  327. 'searchWith',
  328. 'whereor',
  329. 'where',
  330. 'fill',
  331. );
  332. foreach ($actions as $action) {
  333. $fields = explode($action, $method);
  334. if (count($fields) > 1 && empty($fields[0]) && !empty($fields[1])) {
  335. $field = $this->snake($fields[1]);
  336. switch ($action) {
  337. case 'whereor':
  338. return $this->doWhere($field, $params, 'OR');
  339. case 'fill':
  340. $this->fill($field, $params[0]);
  341. return $this;
  342. default:
  343. return $this->doWhere($field, $params);
  344. }
  345. }
  346. }
  347. return $this;
  348. }
  349. }