Laravel-将空值插入数据库

时间:2018-11-28 05:07:40

标签: php mysql arrays laravel loops

您好,我想向数据库中插入一个空值,但是我不知道该怎么办给一个错误

如何插入一个空值来输入文本并将其设置为null到数据库,因为我这样做是错误的,因为数据库的行没有值。我该如何做到没有错误。

这是我的 错误

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

  

SQLSTATE [23000]:违反完整性约束:1048列“标题”   不能为null(SQL:插入awardstitledescription,   awards_imageupdated_atcreated_at)值(,,a:0:{},   2018-11-28 10:29:35,2018-11-28 10:29:35))

我的 控制器

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();
            }

}

2 个答案:

答案 0 :(得分:1)

进行新的迁移

php artisan make:migration fix_title_in_table_awards --table=awards

然后在创建的迁移中首先删除该列,然后重新创建该列使其可为空。.

Schema::table('awards', function (Blueprint $table) {
    $table->dropColum('title');
});

Schema::table('awards', function (Blueprint $table) {
    $table->string('title')->nullable();
});

请务必执行此操作,因为您将丢失该列中的所有数据...也许您可以将title的实际值复制到另一列,直到进行更改为止...

答案 1 :(得分:1)

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

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

我希望这对您有帮助

相关问题