laravel框架model类简单模板

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;
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值