Laravel新模型缺少created_at和updated_at字段

时间:2020-01-03 09:44:37

标签: laravel eloquent

当我使用new Model在控制器更新功能中创建新模型时,它缺少created_atupdated_at。因此,我收到错误409,因为它无法执行查询。知道为什么这两个字段丢失了吗?

$branchItem = Branch::where('id', $branch['branchId'])->get()->first();

// if there is no record with branchId create new one
if (!$branchItem) {
    $branchItem = new Branch;
}
$branchItem->id= $branch['branchId'];

$branchItem->save();

4 个答案:

答案 0 :(得分:1)

手动创建created_atupdated_at列不是最佳实践,但可以解决您的问题

始终使用laravel迁移来创建表格

  Schema::create('example', function (Blueprint $table) {
            $table->bigIncrements('id');

            $table->timestamps();

        });

此处$table->timestamps();负责创建这两​​个字段

答案 1 :(得分:1)

您也可以查看Laravel Migration

的文档

您还可以在迁移文件中遵循以下代码

Schema::create('table_name', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->timestamps(); // this field is able to create your created_at and updated_at field in DB.
});

因此,您必须在上面的迁移文件中添加以上代码 project_folder / database / migrations / migration_file

添加此行后,您必须在终端中运行迁移命令

php artisan migrate:refresh

注意:运行此命令时,这将刷新所有表的数据并重置结构

希望这会引导您解决问题。

答案 2 :(得分:0)

您在表中缺少created_at和updated_at,将其作为时间戳,将updated_at作为NULL

答案 3 :(得分:0)

尝试像这样更改代码。

$branchItem = Branch::where('id', $branch['branchId'])->first();

// if there is no record with branchId create new one
if (!$branchItem) {
    $branchItem = new Branch;
    $branchItem->id= $branch['branchId'];
    $branchItem->save();
} else {
    echo "Record Exist";
}