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

2025-05-27 0 47

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

Model里的代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23
<?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');

}

}

新增的代码

?

1

2

3

4

5

6

7

8

9

10
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

?

1

2

3

4

5

6

7

8

9

10
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

?

1

2

3

4

5

6

7

8

9

10

11
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插入数据,字段created_at0000的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。

原文链接:https://blog.csdn.net/lanwithyu/article/details/74853268

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 解决Laravel 使用insert插入数据,字段created_at为0000的问题 https://www.kuaiidc.com/70834.html

相关文章

发表评论
暂无评论