* [ ] CurdTrait.php
* [ ] 功能
* 簡單的封裝CURD操作,在項目里面操作數據庫表的 Model 層里面 use CurdTrait
* 把常用的功能簡單封裝,方便維護,當底層框架 mysql 操作類方法改變的時候,只需要修改該文件即可
* 文件路徑:/home/wwwroot/project/application/lib/model/Common/CurdTrait.php
~~~
<?php
namespace model\Common;
/**
* Trait CurdTrait
* 針對數據庫的 CURD 操作,增、刪、改、查
* 用法:在需要的 Model 中 use CurdTrait;
* 并且這個 Model 中必須定義靜態成員變量:
* 假設 model 文件為 UserModel
* 如果在 UserModel 中定義的成員變量 $tabName 為空,那么該 trait 會自動獲取當前類名,去截取到 user 表名
* 同理 UserLogModel,如果定義的成員變量 $tabName 為空,那么該 trait 會自動獲取當前類名,去截取到 user_log 表名
* 例如:
* protected static $dbObj = 'Admin'; //操作的數據庫
* protected static $tabName = 'admin'; //操作的表名
* protected static $tabId = 'id'; //[如果沒有,就不需要定義] 該表的主鍵
* @package model\Common
* @author YoY
*/
trait CurdTrait
{
//當前model操作的表對象
protected static $tabObj = false;
/**
* 下劃線轉駝峰
* @param string $str
* @return string|string[]|null
* @author YoY
*/
public static function lineToHump($str = '')
{
if (empty($str)) {
return '';
}
$str = preg_replace_callback('/([-_]+([a-z]{1}))/i', function ($matches) {
return strtoupper($matches[2]);
}, $str);
return empty($str) ? '' : $str;
}
/**
* 駝峰轉下劃線
* @param string $str
* @return string|string[]|null
* @author YoY
*/
public static function humpToLine($str = '')
{
if (empty($str)) {
return '';
}
$str = preg_replace_callback('/([A-Z]{1})/', function ($matches) {
return '_' . strtolower($matches[0]);
}, $str);
$str = ltrim($str, '_');
return empty($str) ? '' : $str;
}
/**
* 記錄允許日志,比如允許中遇到的異常
* @param $message
* @return bool
* @author YoY
*/
public static function runLog($message)
{
try {
//如果 seaslog 拓展沒有安裝,就不記錄異常日志了
if (!extension_loaded('seaslog')) {
return false;
}
if (is_array($message) || is_object($message)) {
$message = json_encode($message, JSON_UNESCAPED_UNICODE);
}
return \SeasLog::info($message);
} catch (\Exception $e) {
return false;
}
}
/**
* 獲取操作的表名
* @return string
* @author YoY
*/
public static function getTabName()
{
// 如果定義的操作的表名為空,默認根據當前類文件名稱去截取 TaskModel 自動找到task表名
if (empty(self::$tabName)) {
$_class_ = explode('\\', __CLASS__);
$key = count($_class_) - 1;
$_class_ = self::humpToLine($_class_[$key]);
$_class_ = explode('_', $_class_);
$key = count($_class_) - 1;
if ($key > 0) unset($_class_[$key]);
self::$tabName = implode('_', $_class_);
}
return self::$tabName;
}
/**
* 獲取表主鍵
* @return string
* @author YoY
*/
public static function getTabId()
{
// 默認主鍵
if (!isset(self::$tabId)) self::$tabId = 'id';
return self::$tabId;
}
/**
* 獲取操作表對象
* @return bool
* @throws \Exception
* @author YoY
*/
public static function getTabOBJ()
{
if (!isset(self::$dbObj)) throw new \Exception('操作表數據庫對象 self::$dbObj 未定義');
self::getTabName();
if (!isset(self::$tabName)) throw new \Exception('操作表名 self::$tabName 未定義');
if (empty(self::$tabObj) || !is_object(self::$tabObj) || empty(self::$tabObj->MyData['table'])) {
$dbObj = '\\mysql\\' . self::$dbObj; //拼接操作表對象的靜態類
self::$tabObj = $dbObj::table(self::$tabName);
}
return self::$tabObj;
}
/**
* 添加記錄
* 例如:user表新增一條記錄 name = YoY pwd = 123456 的記錄到表中
* 返回添加成功的主鍵:UserModel::add( ['name' => 'YoY', 'pwd' => 123456] );
* 返回添加成功的影響行數:UserModel::add( ['name' => 'YoY', 'pwd' => 123456], 'row' );
* 如果只是需要返回sql語句:UserModel::add( ['name' => 'YoY', 'pwd' => 123456], 'demo' );
* @param array $data [要新增的數據]
* @param string $get_sql [返回的形式]
* @return bool
* @author YoY
*/
public static function add($data = [], $get_sql = '')
{
if (empty($data) || !is_array($data)) {
return false;
}
try {
// 如果沒有定義主鍵,那么就只能返回影響的行數
if (!isset(self::$tabId) && empty($get_sql)) $get_sql = 'row';
return self::getTabOBJ()->data($data)->insert($get_sql);
} catch (\Exception $e) {
// 記錄異常日志
self::runLog($e->getMessage());
return false;
}
}
/**
* 批量添加記錄
* 例如:user表批量添加記錄 name = 1, pwd = 123 和 name = 2, pwd = 321 的記錄
* 用法1:UserModel::addAll( [ ['name'=>1, 'pwd' => 123], [ 'name' => 2, 'pwd' => 321] ] );
* 需要返回sql語句:UserModel::addAll( [ ['name'=>1, 'pwd' => 123], [ 'name' => 2, 'pwd' => 321] ], 'demo' );
* @param array $data
* @param string $get_sql
* @return bool
* @author YoY
*/
public static function addAll($data = [], $get_sql = '')
{
if (empty($data)) {
return false;
}
if (empty(self::$tabId) && empty($get_sql)) {
$get_sql = 'row';
}
try {
return self::getTabOBJ()->data($data)->add($get_sql);
} catch (\Exception $e) {
// 記錄異常日志
self::runLog($e->getMessage());
return false;
}
}
/**
* 刪除記錄
* 例如:user表刪除一個id為1的記錄
* 用法1:UserModel::delete( 1 );
* 用法2:UserModel::delete( '1' );
* 用法3:UserModel::delete( ['id' => 1] );
* 用法4:UserModel::delete( ['id' => '1'] );
* 如果只是返回sql語句:UserModel::delete( ['id' => 1], 'demo' );
* @param array $where [刪除記錄的where條件]
* @param string $get_sql [是否只返回sql語句,如果寫入demo,就是返回sql語句]
* @return bool
* @author YoY
*/
public static function delete($where = [], $get_sql = '')
{
if (!is_array($where) && !is_string($where) && !is_int($where)) {
return false;
}
if (is_array($where) && empty($where)) {
return false;
}
if (is_string($where) && empty($where) && $where !== '0') {
return false;
}
// 不是一個數組,那么就是想通過主鍵去刪除
if (!is_array($where)) {
$where = intval($where);
// 如果不存在主鍵定義,或者定義了卻為空,就返回失敗
if (empty(self::getTabId())) {
return false;
}
// 存在主鍵定義,就自動組裝主鍵的where條件
$where = [self::getTabId() => $where];
}
try {
return self::getTabOBJ()->where($where)->delete($get_sql);
} catch (\Exception $e) {
// 記錄異常日志
self::runLog($e->getMessage());
return false;
}
}
/**
* 修改記錄
* 例如:user表修改id字段為1的記錄中的name為new name
* 用法1:UserMode::save( 1, ['name' => 'new name'] );
* 用法2:UserModel::save( '1', ['name' => 'new name'] );
* 用法3:UserModel::save( ['id' => 1], ['name' => 'new name'] );
* 用法4:UserModel::save( ['id' => '1'], ['name' => 'new name'] );
* 用法5:UserModel::save( ['id' => 1, 'name' => 'new name'] );
* 用法6:UserModel::save( ['id' => '1', 'name' => 'new name'] );
* 如果只是返回sql語句:UserModel::save( ['id' => 1], ['name' => 'new name'], 'demo' );
* @param array $where [要修改的where條件 ]
* @param array $data [要修改新的數據值]
* @param string $get_sql [是否只返回sql語句,如果寫入demo,就是返回sql語句]
* @return bool
* @author YoY
*/
public static function save($where = [], $data = [], $get_sql = '')
{
if (!is_array($where) && !is_string($where) && !is_int($where)) {
return false;
}
if (is_array($where) && empty($where)) {
return false;
}
if (is_string($where) && empty($where) && $where !== '0') {
return false;
}
if (!is_array($where)) {
// 如果傳入的where條件是以主鍵,那么就組裝主鍵條件
// 對應使用場景: $tabObj->save( 1, ['name'=>'new name'] );
// 對應使用場景: $tabObj->save( '0', ['name'=>'new name'] );
// 防止有些表的主鍵是有0存在的時候
$where = intval($where);
if (empty(self::getTabId())) {
return false;
}
$where = [self::getTabId() => $where];
} else {
// 如果傳入的是where條件,且where條件中含有主鍵,并且data是空
// 對應使用場景: $tabObj->save( ['id'=>1,'name'=>'new name'] );
if (is_array($where) && empty($data)) {
// 如果是想按照主鍵來更新,但是又沒有定義主鍵名稱或者定義的主鍵名稱為空
if (empty(self::getTabId())) {
return false;
}
// 然后更新的數據里面,主鍵字段不存在
if (!isset($where[self::getTabId()])) {
return false;
}
$data = $where;
$where = [self::getTabId() => $where[self::getTabId()]];
unset($data[self::getTabId()]);
}
}
// 防止where條件或更新的數據都為空
if (empty($where) || empty($data)) {
return false;
}
try {
return self::getTabOBJ()->where($where)->data($data)->update($get_sql);
} catch (\Exception $e) {
// 記錄異常日志
self::runLog($e->getMessage());
return false;
}
}
/**
* 根據where條件查詢單條數據
* 例如:user表獲取一條ID為1的記錄的name、pwd字段的值
* 用法1:UserModel::find( 1, 'name,pwd' );
* 用法2:UserModel::find( '1', 'name,pwd' );
* 用法3:UserModel::find( ['id' => 1], 'name,pwd' );
* 用法4:UserModel::find( ['id' => '1'], 'name,pwd' );
* 如果只是返回sql語句:$tabObj->find( ['id' => '1'], 'name,pwd', [], 'demo' );
* @param array $where
* @param string $field
* @param $other array [ 其他屬性, 比如排序order]
* @param string $get_sql [是否只返回sql語句,如果寫入demo,就是返回sql語句]
* @return array
* @author YoY
*/
public static function find($where = [], $field = '', $other = [], $get_sql = '')
{
if (!is_string($field)) {
return [];
}
// 排序規則
$order = $other['order'] ?? '';
$order = self::data_format_order($order);
// 如果where條件不是數組,那么就是想通過主鍵來查詢
if (!is_array($where)) {
// 想通過主鍵查詢,可是又沒有設置主鍵名稱,那么就返回空數組
if (empty(self::getTabId())) {
return [];
}
// 主鍵查詢
$where = [self::getTabId() => intval($where)];
}
try {
return self::getTabOBJ()->where($where)->field($field)->order($order)->find($get_sql);
} catch (\Exception $e) {
// 記錄異常日志
self::runLog($e->getMessage());
return [];
}
}
/**
* 根據where條件查詢數據
* 例如:user表獲取 state 為 1的 所有記錄,只要字段 id,name,pwd,state,并且按照 id降序,state降序
* 用法1:UserModel::select( ['state' => 1], 'id,name,pwd,state','id DESC,state DESC')
* 用法2:UserModel::select( ['state' => 1], 'id,name,pwd,state','id DESC,state DESC')
* @param array $where [查詢的where條件]
* @param string $field
* @param string $order
* @param array $other [ 這個是其他附加屬性,比如限制查詢的條數,limit,默認limit是查詢所有]
* @param string $get_sql [是否只返回sql語句,如果寫入demo,就是返回sql語句]
* @return array
* @author YoY
*/
public static function select($where = [], $field = '', $order = '', $other = [], $get_sql = '')
{
// 如果排序為空,默認以主鍵降序來排序
if (empty($order)) {
$order = empty(self::getTabId()) ? '' : self::getTabId() . ' DESC';
}
// 如果排序為數組,那么需要拼接為字符串 ['id' => 'DESC', 'state' => 'ASC'] 轉為 'id DESC,state ASC'
$order = self::data_format_order($order);
// 限制數量
$limit = $other['limit'] ?? 'all';
// 分組
$group = $other['group'] ?? '';
//針對字段查詢的時候,可能需要某個字段作為數組的key返回
$fieldBox = explode('|', $field);
$field_key = '';
if (count($fieldBox) > 1) {
$field = $fieldBox[0];
$field_key = $fieldBox[1];
}
try {
$tabObj = self::getTabOBJ()->where($where)->order($order)->field($field, $field_key);
// 判斷是否為查詢所有,如果不是查詢所有,那么就增加一個連貫操作limit,限制查詢的數量
if ($limit !== 'all') {
$tabObj = $tabObj->limit($limit);
}
if (!empty($group)) {
$tabObj = $tabObj->group($group);
}
return $tabObj->select($get_sql);
} catch (\Exception $e) {
// 記錄異常日志
self::runLog($e->getMessage());
print_r($e->getMessage());
return [];
}
}
/**
* 分頁查詢數據
* @param int $page [ 頁碼 ]
* @param int $num [ 每頁總條數 ]
* @param array $other [ 其他屬性,比如 查詢條件where(array), 排序order(array or string), 返回字段field(string) ]
* @return array
* @author YoY
*/
public static function getPage($page = 1, $num = 50, $other = [])
{
$where = $other['where'] ?? [];
$order = $other['order'] ?? '';
$field = $other['field'] ?? '';
// 整理排序
$order = self::data_format_order($order);
try {
$data = self::getTabOBJ()->where($where)->order($order)->field($field)->page($num, $page);
} catch (\Exception $e) {
$data = array(
'page' => array(
'total' => 0,
'pages' => 0,
'top' => 0,
'next' => 0,
'page' => $page,
'count' => $num,
'head' => 0,
),
'list' => [],
);
}
return $data;
}
/**
* 統計數量
* @param $where
* @param string $field
* @param array $other
* @return int
*/
public static function count( $where, $field = '*', $other = [])
{
$mode = $other['mode'] ?? '';
$type = $other['type'] ?? '';
$come = $other['come'] ?? '';
try{
return self::getTabOBJ()->where($where)->count($field, $mode, $type, $come);
}catch ( \Exception $e ){
return 0;
}
}
/**
* 整理排序
* @param string $order
* @return string
* @author YoY
*/
protected static function data_format_order($order = '')
{
if (!empty($order) && is_array($order)) {
$tmp_order = [];
//如果是數組,組裝為字符串
foreach ($order as $field_name => $field_val) $tmp_order[] = $field_name . ' ' . $field_val;
$order = implode(',', $tmp_order);
}
return $order;
}
/**
* 復制表結構
* @param $table
* @param string $newtable
* @return bool
*/
public static function creste($table, $newtable = '')
{
try{
$dbObj = '\\mysql\\' . self::$dbObj;
return $dbObj::creste($table, $newtable);
} catch ( \Exception $e ) {
return false;
}
}
/**
* 開始事務
* @return bool
*/
public static function beg()
{
try {
$dbObj = '\\mysql\\' . self::$dbObj;
$dbObj::beg();
return true;
} catch (\Exception $e) {
return false;
}
}
/**
* 提交事務
* @return bool
*/
public static function com()
{
try {
$dbObj = '\\mysql\\' . self::$dbObj;
$dbObj::com();
return true;
} catch (\Exception $e) {
return false;
}
}
/**
* 事務回滾
* @return bool
*/
public static function rol()
{
try {
$dbObj = '\\mysql\\' . self::$dbObj;
$dbObj::rol();
return true;
} catch (\Exception $e) {
return false;
}
}
/**
* 獲取操作的類對象
* @return string
*/
protected static function getDbOBJ()
{
//拼接操作表對象的靜態類
return '\\mysql\\'.self::$dbObj;
}
/**
* 判斷數據庫的某個表是否存在
* @param $table
* @return bool
*/
public static function mysql_if_table($table)
{
try {
return (self::getDbOBJ())::mysql_if_table($table);
} catch ( \Exception $e ) {
return false;
}
}
/**
* @param $data
* @param string $field
* @return bool
*/
protected static function tabname($data, $field = '')
{
try {
return (self::getDbOBJ())::tabname($data, $field);
} catch ( \Exception $e ) {
return false;
}
}
/**
* 聯合表
* @param $data
* @param bool $type
* @return bool
*/
protected static function union($data, $type = false)
{
try {
return (self::getDbOBJ())::union($data, $type);
} catch ( \Exception $e ) {
return false;
}
}
}
~~~
- 開始使用
- 配置文件
- 路由模式
- AutoLoad類
- 啟動文件
- __construct
- SetRouting
- SetAlias
- SetStop
- SetError
- Access
- SetWorker
- SetClassFile
- SetClassDir
- Run
- OpenLoad
- LinuxStartAll
- Session類
- 使用說明
- set
- get
- delete
- pull
- has
- id
- Cookie類
- 使用說明
- set
- get
- delete
- pull
- has
- TempLets類
- 模板語法
- 模板標簽
- html
- show
- assign
- obtain
- Request類
- get
- post
- host
- referer
- getip
- localip
- header
- body
- file
- scheme
- protocolversion
- uri
- path
- querystring
- method
- Response
- SendFile
- FileStream
- SendData
- SetStatus
- SetHead
- SetMime
- WebSend
- redirect
- dumpJson
- dump
- come
- ps
- Frame類
- GetWeb
- ViewFile
- RoutingData
- SetClassFile
- SetClassDir
- GetMime
- FileMime
- LoadDir
- StartDir
- IsJson
- ArrJson
- JsonFormat
- ObStart
- GetConfig
- ConfigDir
- TempDir
- GetRunData
- GetStatic
- IsDebug
- SetDebug
- GetDebugInfo
- GlobalVariables類
- 使用說明
- set
- get
- delete
- pull
- has
- id
- Mysql類
- 新版本
- 第三方
- Thinkorm
- Medoo
- 舊版本
- Mysql 配置格式
- 項目中操作數據庫
- 項目場景
- 項目數據庫配置
- 項目數據庫中間類
- 項目中操作數據表
- 連貫操作
- where
- table
- data
- order
- field
- limit
- page
- group
- having
- join
- tabname
- union
- sql
- link
- link_base
- lock
- CURD 操作
- 寫入數據
- 數據刪除
- 數據查詢
- 數據更新
- 數據統計操作
- count
- sum
- max
- min
- avg
- 操作DEMO
- CurdTrait.php
- 項目Model層操作表.md
- Curl類
- Method類
- SslAes類
- layui_zqadmin