Model.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. <?php
  2. namespace daswork;
  3. use daswork\Config;
  4. use daswork\db\Mysql;
  5. class Model
  6. {
  7. // 查询次数
  8. public static $queryTimes = 0;
  9. // 执行次数
  10. public static $executeTimes = 0;
  11. // 数据库连接参数配置
  12. protected $connection = [];
  13. // 数据库查询对象池
  14. protected static $links = [];
  15. // 当前类名称
  16. protected $class;
  17. // 当前模型名称
  18. protected $name;
  19. // 当前查询对象
  20. protected $query;
  21. // 当前数据表名称(含前缀)
  22. protected $tablename = '';
  23. // 当前数据表名称(不含前缀)
  24. protected $table = '';
  25. // 当前数据表主键
  26. protected $pk;
  27. // 当前数据表前缀
  28. protected $prefix = '';
  29. // 查询参数
  30. protected $options = [];
  31. // 最近查询的 sql 语句
  32. public $sql = '';
  33. /**
  34. * 初始化过的模型.
  35. *
  36. * @var array
  37. */
  38. protected static $initialized = [];
  39. public function __construct()
  40. {
  41. // 当前类名
  42. $this->class = get_called_class();
  43. if (empty($this->name)) {
  44. // 当前模型名
  45. $name = str_replace('\\', '/', $this->class);
  46. $this->name = basename($name);
  47. }
  48. // 合并数据库配置
  49. if (!empty($this->connection) && is_array($this->connection)) {
  50. $connection = array_merge(Config::get('db'), $this->connection);
  51. } else {
  52. $connection = Config::get('db');
  53. }
  54. $this->connection = $connection;
  55. // 设置当前数据表和模型名
  56. if (isset($connection['prefix'])) {
  57. $this->prefix = $connection['prefix'];
  58. }
  59. if (!empty($this->table)) {
  60. $this->tablename = $this->prefix . $this->table;
  61. } else {
  62. $this->tablename = $this->prefix . uncamelize($this->name);
  63. }
  64. // 执行初始化操作
  65. $this->initialize();
  66. }
  67. /**
  68. * 初始化模型
  69. * @access protected
  70. * @return void
  71. */
  72. protected function initialize()
  73. {
  74. $class = get_class($this);
  75. if (!isset(static::$initialized[$class])) {
  76. static::$initialized[$class] = true;
  77. static::init();
  78. }
  79. }
  80. /**
  81. * 初始化处理
  82. * @access protected
  83. * @return void
  84. */
  85. protected static function init()
  86. {
  87. }
  88. /**
  89. * 获取当前模型的查询对象
  90. * @access public
  91. * @param bool $buildNewQuery 创建新的查询对象
  92. * @return Query
  93. */
  94. public function getQuery($buildNewQuery = false)
  95. {
  96. if ($buildNewQuery) {
  97. return Mysql::connect($this->connection);
  98. } elseif (!isset(self::$links[$this->class])) {
  99. // 创建模型查询对象
  100. self::$links[$this->class] = Mysql::connect($this->connection);
  101. }
  102. return self::$links[$this->class];
  103. }
  104. /**
  105. * 指定默认数据表名(含前缀)
  106. * @access public
  107. * @param string $table 表名
  108. * @return $this
  109. */
  110. public function setTablename($tablename)
  111. {
  112. $this->tablename = $tablename;
  113. }
  114. /**
  115. * 得到当前或者指定名称的数据表
  116. * @access public
  117. * @param string $name
  118. * @return string
  119. */
  120. public function getTablename()
  121. {
  122. return $this->tablename;
  123. }
  124. /**
  125. * 执行sql
  126. * @param string $sql
  127. * @return mixd $res
  128. */
  129. public function exec($sql)
  130. {
  131. @$res = $this->getQuery()->exec($sql);
  132. $this->$sql = $sql;
  133. return $res;
  134. }
  135. public function query($sql)
  136. {
  137. $result = $this->getQuery()->query($sql);
  138. $this->$sql = $sql;
  139. return $result;
  140. }
  141. public function lastInsertRowID ()
  142. {
  143. $result = $this->getQuery()->lastInsertRowID();
  144. return $result;
  145. }
  146. public function lastErrorMsg()
  147. {
  148. return $this->getQuery()->lastErrorMsg();
  149. }
  150. /**
  151. * 查询数组列表
  152. */
  153. public function select($sql)
  154. {
  155. $result = $this->getQuery()->query($sql);
  156. $data = array();
  157. while ($arr = $result->fetch_assoc()) {
  158. $data[] = $arr;
  159. }
  160. return $data;
  161. }
  162. /**
  163. * 列表结果集
  164. */
  165. public function list($where='')
  166. {
  167. $sql = "select * from $this->tablename $where;";
  168. return $this->select($sql);
  169. }
  170. /**
  171. * 查询一条
  172. */
  173. public function getOneById($id, $tablename='')
  174. {
  175. $tablename = $tablename ? $tablename : $this->tablename;
  176. $sql = "SELECT * FROM `$tablename` WHERE `id`=$id;";
  177. $result = $this->getQuery()->query($sql);
  178. // var_dump($result);
  179. $data = $result->fetch_all(MYSQLI_ASSOC);
  180. // var_dump($data);
  181. return $data;
  182. }
  183. /**
  184. * 单列合计
  185. */
  186. public function sumColumn($column, $tablename)
  187. {
  188. $tablename = $tablename ? $tablename : $this->tablename;
  189. $sql = "SELECT sum(`$column`) as sumData FROM `$tablename`;";
  190. $result = $this->getQuery()->query($sql);
  191. // $data = $result->fetch_assoc();
  192. // var_dump($data['sumData']);exit;
  193. if ($data = $result->fetch_assoc()) {
  194. return $data['sumData'];
  195. }
  196. return 0;
  197. }
  198. public function listByName($name='', $order = '', $desc = false)
  199. {
  200. $where = "";
  201. if ($name) {
  202. $where = " where name like '%$name%'";
  203. }
  204. if ($order) {
  205. $where .= " order by $order";
  206. if ($desc) {
  207. $where .= " desc";
  208. } else {
  209. $where .= " asc";
  210. }
  211. }
  212. $sql = "select * from $this->tablename $where;";
  213. $res = $this->select($sql);
  214. return $res;
  215. }
  216. /**
  217. * save
  218. */
  219. public function save($data)
  220. {
  221. $columns = "";
  222. $values = "";
  223. foreach ($data as $key => $value) {
  224. $columns .= "`" . $key . "`,";
  225. $values .= "'" . $value . "',";
  226. }
  227. $columns = rtrim($columns, ',');
  228. $values = rtrim($values, ',');
  229. $sql = "INSERT INTO `$this->tablename`(" . $columns . ") VALUES(". $values . ");";
  230. return $this->exec($sql);
  231. }
  232. /**
  233. * updateById
  234. */
  235. public function updateById($data)
  236. {
  237. $id = $data['id'];
  238. unset($data['id']);
  239. $columns = "";
  240. foreach ($data as $key => $value) {
  241. $columns .= "`" . $key . "`='" . $value ."',";
  242. }
  243. $columns = rtrim($columns, ',');
  244. $sql = "UPDATE `$this->tablename` SET $columns WHERE `id`=$id";
  245. return $this->exec($sql);
  246. }
  247. /**
  248. * deleteByIds
  249. */
  250. public function deleteById($id)
  251. {
  252. $sql = "DELETE FROM `$this->tablename` WHERE `id` IN(";
  253. if (is_array($id)) {
  254. for ($i=0; $i < count($id); $i++) {
  255. $sql .= $id[$i] . ',';
  256. }
  257. $sql = rtrim($sql, ',');
  258. $sql .= ");";
  259. } else {
  260. $sql = "DELETE FROM `$this->tablename` WHERE `id`=$id;";
  261. }
  262. return $this->exec($sql);
  263. }
  264. // public function __destruct()
  265. // {
  266. // $this->query->close();
  267. // }
  268. function add($data){
  269. //列名数组
  270. $cols=array();
  271. //列值数组
  272. $vals=array();
  273. foreach($data as $key=>$val){
  274. $cols[]="`".$key."`";
  275. $vals[]="'".$val."'";
  276. }
  277. //$cols=array(0=>'`titlekey`',1=>'`contentkey`'); //
  278. //$vals=array(0=>"'titleval'",1=>"'contentval'"); //
  279. //用","将数组每个元素重新拼接起来
  280. $str_cols=implode(',',$cols); //$str_cols= `titlekey`,`contentkey`
  281. $str_vals=implode(',',$vals); //$str_vals= 'titleval','contentval'
  282. //执行插入数据
  283. $sql="insert into ".$this->tablename."($str_cols) values($str_vals);";
  284. return $this->getQuery()->insert($sql );
  285. }
  286. function update($data,$where){
  287. $wherestr = '';
  288. if(!empty($where)){
  289. $wherestr .=' where '.$where;
  290. }
  291. $par_array=array();
  292. foreach($data as $key=>$val){
  293. $par_array[]="`".$key."`="."'".$val."'";
  294. }
  295. //用","将修改列和列值的数组里每个元素重新拼接起来
  296. $param=implode(',',$par_array);
  297. $sql = "update ".$this->tablename." set ".$param." ".$wherestr." ";
  298. return $this->getQuery()->query($sql);
  299. }
  300. function get_lists($where, $limit=''){
  301. $wherestr = '';
  302. if(!empty($where)){
  303. $wherestr .=' where '.$where;
  304. }
  305. $sql = 'select * from '.$this->tablename.$wherestr . $limit;
  306. // echo $sql;
  307. return $this->getQuery()->select($sql);
  308. }
  309. function get_sum($where){
  310. $wherestr = '';
  311. if(!empty($where)){
  312. $wherestr .=' where '.$where;
  313. }
  314. $sql = "select count(*) as sum from ".$this->tablename.$wherestr;
  315. $data = $this->getQuery()->get_row($sql);
  316. return $data['sum'];
  317. }
  318. function get_one($where){
  319. $wherestr = '';
  320. if(!empty($where)){
  321. $wherestr .=' where '.$where;
  322. }
  323. $sql = "select * from ".$this->tablename.$wherestr;
  324. //var_dump($sql);exit;
  325. $data = $this->getQuery()->get_row($sql);
  326. return $data;
  327. }
  328. }