据官方文档的说明,使用Eloquent ORM,插数据库的时候可以自动生成created_at,updated_at,代码如下:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Notice extends Model { protected $guarded = []; //获取部门名称 public function fromDep(){ return $this->belongsTo('App\Models\Department','from','id'); } public function toDep(){ return $this->belongsTo('App\Models\Department','to','id'); } public function toUser(){ return $this->belongsTo('App\User','create_user','id'); } }
public function store(Request $request) { $data = $request->only(['title','sort','level','from','content','document']); $data['creater'] = Auth::user()->id; if(Notice::insert($data)){ return ResponseLayout::apply(true); }else{ return ResponseLayout::apply(false); } }
插入一条数据,数据库中created_at和updated_at字段为0000-00-00 00:00:00。
原因分析:原生的插入语句,Laravel是不会自动帮你插入created_at和updated_at字段的。
解决方法
create
public function store(Request $request) { $data = $request->only(['title','sort','level','from','content','document']); $data['creater'] = Auth::user()->id; if(Notice::create($data)){ return ResponseLayout::apply(true); }else{ return ResponseLayout::apply(false); } }
save
public function store(Request $request) { $data = $request->only(['title','sort','level','from','content','document']); $data['creater'] = Auth::user()->id; $notice = new Notice($data); if($notice->save()){ return ResponseLayout::apply(true); }else{ return ResponseLayout::apply(false); } }
扫码二维码 获取免费视频学习资料
- 本文固定链接: http://phpxs.com/post/6619/
- 转载请注明:转载必须在正文中标注并保留原文链接
- 扫码: 扫上方二维码获取免费视频资料
查 看2022高级编程视频教程免费获取