主頁 > 知識庫 > 解決Laravel 使用insert插入數(shù)據(jù),字段created_at為0000的問題

解決Laravel 使用insert插入數(shù)據(jù),字段created_at為0000的問題

熱門標(biāo)簽:Linux服務(wù)器 服務(wù)器配置 團購網(wǎng)站 科大訊飛語音識別系統(tǒng) 阿里云 Mysql連接數(shù)設(shè)置 銀行業(yè)務(wù) 電子圍欄

據(jù)官方文檔的說明,使用Eloquent ORM,插數(shù)據(jù)庫的時候可以自動生成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);
    }
  }

插入一條數(shù)據(jù),數(shù)據(jù)庫中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);
    }
  }

以上這篇解決Laravel 使用insert插入數(shù)據(jù),字段created_at為0000的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • Laravel timestamps 設(shè)置為unix時間戳的方法
  • laravel model模型定義實現(xiàn)開啟自動管理時間created_at,updated_at

標(biāo)簽:萍鄉(xiāng) 衢州 蚌埠 江蘇 衡水 廣元 棗莊 大理

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《解決Laravel 使用insert插入數(shù)據(jù),字段created_at為0000的問題》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266