解决Laravel 使用insert插入数据,字段created_at为0000的问题
据官方文档的说明,使用EloquentORM,插数据库的时候可以自动生成created_at,updated_at,代码如下:
Model里的代码:
belongsTo('App\Models\Department','from','id'); } publicfunctiontoDep(){ return$this->belongsTo('App\Models\Department','to','id'); } publicfunctiontoUser(){ return$this->belongsTo('App\User','create_user','id'); } }
新增的代码
publicfunctionstore(Request$request) { $data=$request->only(['title','sort','level','from','content','document']); $data['creater']=Auth::user()->id; if(Notice::insert($data)){ returnResponseLayout::apply(true); }else{ returnResponseLayout::apply(false); } }
插入一条数据,数据库中created_at和updated_at字段为0000-00-0000:00:00。
原因分析:原生的插入语句,Laravel是不会自动帮你插入created_at和updated_at字段的。
解决方法
create
publicfunctionstore(Request$request) { $data=$request->only(['title','sort','level','from','content','document']); $data['creater']=Auth::user()->id; if(Notice::create($data)){ returnResponseLayout::apply(true); }else{ returnResponseLayout::apply(false); } }
save
publicfunctionstore(Request$request) { $data=$request->only(['title','sort','level','from','content','document']); $data['creater']=Auth::user()->id; $notice=newNotice($data); if($notice->save()){ returnResponseLayout::apply(true); }else{ returnResponseLayout::apply(false); } }
以上这篇解决Laravel使用insert插入数据,字段created_at为0000的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。