# Curd trait引入
后臺使用Curd trait, 能大大提高開發效率以及代碼的可復用性, 文件位置:`app/admin/traits/Curd.php`
> 默認的CURD方法有:
| 參數 | 說明 |
| --- | --- |
| index | 列表 |
| add | 添加 |
| edit | 編輯 |
| delete | 刪除 |
| export | 導出 |
| modify | 屬性修改 |
# 使用方法
* 在類里面引入`use \app\admin\traits\Curd;`
* 在類直接引入`use EasyAdmin\annotation\NodeAnotation;`,(備注:因為方法內有使用到權限注解,至少要引入該類,不然會在節點更新的時候報出異常)
* 初始化當前模型
> 代碼示例
~~~
<?php
namespace app\admin\controller;
use app\admin\model\SystemConfig;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
/**
* @ControllerAnnotation(title="測試控制器")
*/
class Test extends AdminController{
use \app\admin\traits\Curd;
public function __construct(App $app){
parent::__construct($app);
$this->model = new SystemConfig();
}
}
~~~
# 覆蓋方法修改
> 因為默認的Curd不適用你的需求,請復制`app/admin/traits/Curd.php`對應的方法到你的控制器下進行覆蓋修改。
# `index()`列表關聯查詢
* 修改控制器的屬性`relationSerach`為true
* 模型關聯請使用該方法`withJoin()`
> 代碼示例`控制器`
~~~
<?php
namespace app\admin\controller\mall;
use app\admin\model\MallGoods;
use app\admin\traits\Curd;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
/**
* @ControllerAnnotation(title="商城商品管理")
*/
class Goods extends AdminController
{
use Curd;
protected $relationSerach = true;
public function __construct(App $app)
{
parent::__construct($app);
$this->model = new MallGoods();
}
/**
* @NodeAnotation(title="列表")
*/
public function index()
{
if ($this->request->isAjax()) {
if (input('selectFields')) {
return $this->selectList();
}
list($page, $limit, $where) = $this->buildTableParames();
$count = $this->model
->withJoin('cate', 'LEFT')
->where($where)
->count();
$list = $this->model
->withJoin('cate', 'LEFT')
->where($where)
->page($page, $limit)
->order($this->sort)
->select();
$data = [
'code' => 0,
'msg' => '',
'count' => $count,
'data' => $list,
];
return json($data);
}
return $this->fetch();
}
}
~~~
> 代碼示例`模型`
~~~
<?php
namespace app\admin\model;
use app\common\model\TimeModel;
class MallGoods extends TimeModel
{
protected $deleteTime = 'delete_time';
public function cate()
{
return $this->belongsTo('app\admin\model\MallCate', 'cate_id', 'id');
}
}
~~~
# `modify()`屬性修改限制
> 為了安全,modify方法默認允許修改的字段有:
* status
* sort
* remark
* is\_delete
* is\_auth
* title
> 如果默認字段不適用你的需求請, 請在控制器下覆蓋該屬性`allowModifyFileds`值即可。
~~~
<?php
namespace app\admin\controller;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
/**
* @ControllerAnnotation(title="測試控制器")
*/
class Test extends AdminController{
use \app\admin\traits\Curd;
protected $allowModifyFileds = ['username','sort'];
}
~~~