Laravel 8 - firstOrCreate() 没有 return 数据库中设置的默认值

Laravel 8 - firstOrCreate() doesn't return Default value set in the DB

我的 MySQL 数据库的字段 formed_id:

的默认值设置为 0
`former_id` bigint(20) NOT NULL DEFAULT 0 

当我使用firstOrCreate()方法插入新记录时,我没有设置formed_id:

$record = Record::firstOrCreate(
   [
      "name" => "myName",
      "nick"  => "myNick",
   ]
);

和输出 returns:

{
   "id": 10,
   "name" => "myName",
   "nick  => "myNick",
   "created_at" => "2020-10-01 00:00:00",
   "updated_at" => "2020-10-01 00:00:00",
}

不包含设置为默认值的 former_id 字段,0


要获取输出模型中的所有字段,我需要执行第二个查询:

$record = Record::firstOrCreate(
   [
      "name" => "myName",
      "nick  => "myNick",
   ]
);
$fullRecord = Record::find($record->id)

在这种情况下,输出 returns 正确:

{
   "id": 10,
   "name" => "myName",
   "nick  => "myNick",
   "former_id" => 0,
   "created_at" => "2020-10-01 00:00:00",
   "updated_at" => "2020-10-01 00:00:00",
}

我不喜欢这个解决方案,因为我需要执行两个查询而不是一个;有没有办法直接从 firstOrCreate() 插入中获取所有字段?

谢谢。

这确实是正确的行为。默认情况下,在创建模型后直接获取模型可能效率非常低。

在您的情况下,您可以向模型添加 $attributes 属性 以实现默认属性并避免执行其他查询。

/**
 * The model's attributes.
 *
 * @var array
 */
protected $attributes = [
    'former_id' => 0,
];

阅读@dave 解决方案:

最终代码应该是:

$record = Record::firstOrCreate(
   [
      "name" => "myName",
      "nick"  => "myNick",
   ]
);
if ($record->wasRecentlyCreated) {
    $record->refresh();
}