Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

Laravel 使用DB::insert()插入数据,字段created_at为0000...?

这是artilce_info

$table->increments('id');
            $table->unsignedInteger('user_id');
            $table->string('title');
            $table->integer('read_num');
            $table->timestamps();

这是插入的代码

        DB::beginTransaction();
        try {
            $artInfoId = DB::table('article_info')->insertGetId([
                'title' => $title,
                'user_id' => $userId,
                'read_num' => 0,
            ]);
            DB::table('article')->insert([
                'art_info_id' => $artInfoId,
                'content' => $body,
            ]);
            DB::commit();
            return redirect()->route('blog.index');
        } catch(Exception $exception) {
            DB::rollBack();
            return back()->withErrors($exception->getMessage())->withInput();
        }

插入一条数据和,数据库中created_atupdated_at字段为0000-00-00 00:00:00


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

通过Query Builder的方式插入数据,laravel是不会自动帮你管理created_at,updated_at这些字段的。你需要通过Model类处理,如:

$artInfo = new ArtInfo([
    'title' => $title,
    'user_id' => $userId,
    'read_num' => 0,
]);
$artInfo->save();

这样就可以自动生成对应时间


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...