核心類
trait CrudModel
{
public function crudSearch(&$q) {}
public function crudGetList($where = [], $with = [], $columns = ["*"]) {
$q = static::query();
if($where) {
if(is_callable($where)) {
$where($q);
} else if(is_array($where)) {
$q->where($where);
}
}
if($with) {
$q->with($with);
}
$this->crudSearch($q);
return $this->paginate($q, $columns);
}
public function crudSave($update, $where = null) {
if(is_string($update)) {
$update = $update::M();
}
if(isset($update[$this->primaryKey])) {
$q = static::query()->where($this->primaryKey, $update[$this->primaryKey]);
if($where) {
if(is_callable($where)) {
$where($q);
} else if(is_array($where)) {
$q->where($where);
}
}
$q = $q->first();
if(!$q) {
throw new QueryException;
}
if($q->fill($update)->save()) {
return $q;
}
return null;
} else {
$m = new static;
if($where) {
$update = array_merge($update, $where);
}
if($m->fill($update)->save()) {
return $m;
}
return null;
}
}
public function crudGetDetail($where = [], $with = [], $columns = ["*"]) {
$q = static::query();
if($where) {
if(is_callable($where)) {
$where($q);
} else if(is_array($where)) {
$q->where($where);
}
} else {
$q->where($this->primaryKey, Request::input("id"));
}
if($columns) {
$q->select($columns);
}
if($with) {
$q->with($with);
}
$m = $q->first();
if(!$m) {
throw new ParamException;
}
return $m->toArray();
}
public function crudDel($callback = null) {
DB::transaction(function () use($callback) {
$ids = IdValidate::M()["id"];
if($callback) {
$callback($ids);
} else {
static::query()
->whereIn($this->primaryKey, $ids)
->delete();
}
});
}
}
統一模型繼承
class Model extends \Illuminate\Database\Eloquent\Model
{
use PaginateFormat, CrudModel;
}
模擬呼叫
public function getCarTagList() {
$r = new CarTagModel;
$r = $r->crudGetList(function($q) {
$all = Request::all();
foreach ($all as $k => $v) {
if($k === "key") {
$q->where("name", "LIKE", "%{$v}%");
}
}
});
return $this->json($r);
}
public function getCarTagDetail() {
$r = new CarTagModel;
$r = $r->crudGetDetail();
return $this->json($r);
}
public function setCarTag() {
$r = new CarTagModel;
$r->crudSave(SetCarTagValidate::class);
return $this->json();
}
public function delCarTag() {
$r = new CarModel;
$r->crudDel();
return $this->json();
}
後記
本作品採用《CC 協議》,轉載必須註明作者和本文連結