laravel框架model类简单模板

来源:互联网 发布:网络电视盒刷机软件 编辑:程序博客网 时间:2024/05/20 06:40
class User extends Model{    //指定模型关联表    protected $table = 'user';    //指定数据库主键    protected $primaryKey = 'id';    //定义时间戳    public $timestamps = false;    //定义时间戳格式    //protected $dateFormat = 'U';    //指定允许批量赋值的字段    protected $fillable = ['id','name','sort','status','author','user','clicks','created_at','updated_at'];    //指定不允许批量赋值的字段    protected $guarded = [];    private static $validate = [        //规则        'rule' => [            'name'   => 'required | min:3 | max:20 | string | unique:book',                 'age'   => 'required | integer',        ],        //提示信息         'message' => [             'required' => ':attribute不能为空',             'min'      => ':attribute字数太少了',             'max'      => ':attribute字数太多了',             'string'   => ':attribute格式错误',             'integer'   => ':attribute必须为数字',             'unique'   => '该:attribute已经存在',         ],        //自定义        'custom' => [            'name'   => '姓名',            'age'   => '年龄'        ]    ];    public function validator($data)    {        return Validator::make(            $data,            self::$validate['rule'],            self::$validate['message'],            self::$validate['custom']        );    }    //自定义时间存储格式    public static function boot()    {        parent::boot();        static::creating(function ($model) {            $date = date('Y-m-d H:i:s');            $model->created_at = $date;            $model->updated_at = $date;            return true;        });        static::updating(function ($model) {            $date = date('Y-m-d H:i:s');            $model->updated_at = $date;            return true;        });    }    //获取格式化好的时间戳    protected function getDateFormat()    {        return time();    }    //没有格式化好的时间    protected function asDateTime($val)    {        return $val;    }}

原创粉丝点击