模型列表自动Where
if (!function_exists('model_where')) {
function model_where(&$model, $where)
{
if (empty($where)) {
return $model;
}
// 使用表结构分析, 自动将传进来的参数根据分析的表结构来决定查询条件
$tableInfo = $model::DB()->select('SHOW FULL FIELDS FROM `' . $model->getTable() . '`');
$tableInfo = object_to_array($tableInfo);
$tableInfo = array_column_to_key($tableInfo, 'Field');
$model = $model::query();
foreach ($tableInfo as $key => $v) {
if (strpos($tableInfo[$key]['Type'], 'int') !== false) {
if (array_key_exists($key, $where) && is_numeric($where[$key])) {
$model = $model->where($key, intval($where[$key]));
}
} else if (strpos($tableInfo[$key]['Type'], 'char') !== false) {
if (!empty($where[$key])) {
$model = $model->where($key, 'like', '%' . $where[$key] . '%');
}
} else if (
strpos($tableInfo[$key]['Type'], 'decimal') !== false
|| strpos($tableInfo[$key]['Type'], 'timestamp') !== false
) {
if (array_key_exists($key . '_from', $where) && $where[$key . '_from'] !== '') {
$model = $model->where($key, '>=', $where[$key . '_from']);
}
if (array_key_exists($key . '_to', $where) && $where[$key . '_to'] !== '') {
$model = $model->where($key, '<', $where[$key . '_to']);
}
if (array_key_exists($key, $where) && $where[$key] !== '') {
$model = $model->where($key, $where[$key]);
}
} else if (strpos($tableInfo[$key]['Type'], 'enum') !== false) {
if (array_key_exists($key, $where)) {
$model = $model->where($key, $where[$key]);
}
}
}
}
}
$where = RequestHelper::get();
$query = new AbcdModel()
model_where($query,$where);
return ResponseHelper::paginator($query->paginate(RequestHelper::getPerPage()), new \App\Transformers\AbcdModelTransformer());
限制不重复写入
if (!function_exists('sql_insert_once')) {
// 写入限制, 确保写入只会被写入一次
function model_sql_insert_once($table, $array, $existsSql = '')
{
$sql0 = [];
$sql1 = [];
foreach ($array as $kq => $kv) {
$sql0[] = '`' . $kq . '`';
if (is_null($kv)) {
$sql1[] = 'NULL';
} else {
$sql1[] = '\'' . addslashes($kv) . '\'';
}
}
// SELECT * FROM `' . $table . '` WHERE AND created_at>NOW()-INTERVAL 5 SECOND
return ' INSERT INTO `' . $table . '`(' . implode(',', $sql0) . ')
SELECT ' . implode(',', $sql1) . ' FROM DUAL WHERE NOT EXISTS(' . $existsSql . ') ';
/*
DB::insert(DB::raw($tmpSql));
$paymentParentId = DB::getPdo()->lastInsertId();
if (empty($paymentParentId)) {
error_responses('支付中 ...');
}
*/
}
}
$sql = model_sql_insert_once('course_orders', $courseOrderHeader, "SELECT * FROM course_orders WHERE
help_code='" . $courseOrderHeader['help_code'] . "'
AND pid='" . $courseOrderHeader['pid'] . "'
AND class_id='" . $courseOrderHeader['class_id'] . "'
AND course_id='" . $courseOrderHeader['course_id'] . "'
AND state=1
AND created_at>NOW()-INTERVAL 60 SECOND");
// DB::insert(DB::raw($sql)) ;
$db = CourseOrderItem::DB();
$db->beginTransaction();
$db->insert($sql);
$orderId = DB::getPdo()->lastInsertId();
if (empty($orderId)){
error_response('下单中');
}