欢迎来到代码驿站!

PHP代码

当前位置:首页 > 软件编程 > PHP代码

解决Laravel 使用insert插入数据,字段created_at为0000的问题

时间:2021-08-06 09:07:00|栏目:PHP代码|点击:

据官方文档的说明,使用Eloquent ORM,插数据库的时候可以自动生成created_at,updated_at,代码如下:

Model里的代码:

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

上一篇:PHP基础之输出缓冲区基本概念、原理分析

栏    目:PHP代码

下一篇:PHP 万年历实现代码

本文标题:解决Laravel 使用insert插入数据,字段created_at为0000的问题

本文地址:http://www.codeinn.net/misctech/164645.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有