gpt4 book ai didi

php - Laravel - 将空值插入数据库

转载 作者:行者123 更新时间:2023-11-29 06:36:43 24 4
gpt4 key购买 nike

您好,我想向我的数据库插入一个空值,但我不知道如何执行此操作,会出现错误

如何插入空值以输入文本并将其设置为空到数据库,正如我这样做的那样,我遇到错误,因为数据库的行没有值。我怎样才能做到这一点而不出错。

这是我的错误

如您所见,我有一个 foreach 循环,因此插入 1 个输入文本值不会在数据库中返回任何内容。

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: insert into awards (title, description, awards_image, updated_at, created_at) values (, , a:0:{}, 2018-11-28 10:29:35, 2018-11-28 10:29:35))

我的 Controller

public function store(Request $request)
{
$this->validate($request, [
'title' => 'nullable',
'description' => 'nullable',
'awards_image.*' => 'image|nullable|max:1999'
]);
$awards = [];
if ($request->has('awards_image'))
{
//Handle File Upload


foreach ($request->file('awards_image') as $key => $file)
{
// Get FileName
$filenameWithExt = $file->getClientOriginalName();
//Get just filename
$filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $file->getClientOriginalExtension();
//Filename to Store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->storeAs('public/awards_images',$fileNameToStore);
array_push($awards, $fileNameToStore);
}

$fileNameToStore = serialize($awards);
}
else
{
$fileNameToStore='noimage.jpg';
}


foreach ($awards as $key => $values) {
$awardsContent = new Award;
$awardsContent->title = $request->title[$key];
$awardsContent->description = $request->description[$key];
$awardsContent->awards_image = $values;
$awardsContent->save();
}

}

最佳答案

如果您不想更改表格,请尝试以下操作:

foreach ($awards as $key => $values) {
$awardsContent = new Award;
$awardsContent->title = !empty($request->title[$key]) ? $request->title[$key] : '';
$awardsContent->description = $request->description[$key];
$awardsContent->awards_image = $values;
$awardsContent->save();
}

}

empty() 中的更多信息:

http://php.net/manual/en/function.empty.php

如果您愿意更改表,请在上面创建一个迁移

Schema::table('awards', function(Blueprint $table) {

$table->string('title')->nullable()->change();

});

当然,您必须将其更改为已有的内容,但重要的部分是 ->nullable()->change(); 该行的其余部分应与您的相同初始迁移。

有关迁移更改的更多信息:

https://laravel.com/docs/5.7/migrations#modifying-columns

希望这有帮助

关于php - Laravel - 将空值插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53512505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com