Laravel Mutator 导致 SQLSTATE 一般错误 1364 字段 'x' 没有默认值

Laravel Mutator causes SQLSTATE general error 1364 field 'x' doesn't have a default value

我一直在调查这个问题,我已经找到了导致这个问题的原因。见问题底部

我正在 Laravel 5.4 并使用 BackPackForLaravel 作为我的管理界面。

我有一个 GenreTableMigration 如下所示:

Schema::create('genres', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('slug')->default('');
    $table->string('image');
    $table->enum('status', ['PUBLISHED', 'DRAFT'])->default('PUBLISHED');
    $table->boolean('featured')->default(0);
    $table->timestamps();
    $table->softDeletes();
});

请注意,image 列不可为空且没有默认值。 在我的模型 Genre 中有这个:

protected $fillable = ['slug', 'name', 'image', 'status', 'featured'];

我的模型中还有 image 列的修改器:

/**
 * Store Image
 */

public function setImageAttribute($value)
{
    $attribute_name = "image";
    $disk = "public";
    $destination_path = "Albums";

    // if the image was erased
    if ($value == null) {
        // delete the image from disk
        \Storage::disk($disk)->delete($this->image);

        // set null in the database column
        $this->attributes[$attribute_name] = null;
    }

    // if a base64 was sent, store it in the db
    if (starts_with($value, 'data:image')) {
        // 0. Make the image
        $image = \Image::make($value);
        // 1. Generate a filename.
        $filename = md5($value . time()) . '.jpg';
        // 2. Store the image on disk.
        \Storage::disk($disk)->put($destination_path . '/' . $filename, $image->stream());
        // 3. Save the path to the database
        $this->attributes[$attribute_name] = $destination_path . '/' . $filename;
    }
}

还有我的 GenresTableSeeder:

$path = base_path('seeder-resources/GenresPhotos');

DB::table('genres')->delete();

$genres = [
    [
        'name' => 'Pop',
        'image' => "$path/Pop.jpeg",
        'status' => 'PUBLISHED',
        'featured' => mt_rand(0, 1),
        'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
        'updated_at' => Carbon::now()->format('Y-m-d H:i:s'),
    ],
];

foreach ($genres as $genre) {
    $this->command->info(print_r($genre));
    Genre::create($genre);
}

当我使用 GenreCrudController 并使用 Add Genre 按钮时,一切正常并创建了行,但是当我尝试为 table 设置种子时,我的控制台出现以下错误.

  [Illuminate\Database\QueryException]                                         
  SQLSTATE[HY000]: General error: 1364 Field 'image' doesn't have a default v  
  alue (SQL: insert into `genres` (`name`, `status`, `featured`, `created_at`  
  , `updated_at`, `slug`) values (Pop, PUBLISHED, 0, 2017-03-10 08:43:15, 201  
  7-03-10 08:43:15, pop))  

即使我将 $genres 数组中的 image 值(这是一个字符串列)设置为 Anything。我也试过像下面这样雄辩地播种:

$genre = new Genre();
$genre->name = 'Pop';
$genre->image = "anything";
$genre->status = 'PUBLISHED';
$genre->featured = 1;
$genre->save();

控制台仍然出现同样的错误。有人知道吗?

更新 所以我将 image 列名称更改为 somestring 并且奇怪的是播种器工作了。我尝试将 image 列放在另一个 table 中,比方说 Articles table 并在我的 ArticlesTableSeeder 中添加 'image' => 'test' 并且它再次起作用。然后我在 Article 模型和 BOOM 中添加了相同的突变器!我的 table 中的 image 输出为 NULL。有人知道为什么我的 setImageAttribute 突变器会导致这个问题吗?

在您的迁移中,请像下面这样更改并尝试:

Schema::create('genres', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name')->nullable();
    $table->string('slug')->nullable()->default('');
    $table->string('image')->nullable();
    $table->enum('status', ['PUBLISHED', 'DRAFT'])->default('PUBLISHED');
    $table->boolean('featured')->default(0);
    $table->timestamps();
    $table->softDeletes();
});

请为您的字符串字段提供 nullable()。

首先:如果你在数据库中使用默认值,请这样做(可以为空): $table->string('slug')->nullable()->default(''); else laravel 没有创建正确的新记录。

其次:尝试使用'image' => $path.'/Pop.jpeg'

我不确定,但也许你必须转义字符串 'image' => $path.'\/Pop.jpeg'

所以我发现 Mutator setImageAttribute 只接受 Null 或 base64 $value 并且我试图播种图像文件,当它失败时我试图播种一个字符串。我想出了这个 Mutator,它工作得很好:

/**
 * Store Image
 */
public function setImageAttribute($value)
{
    $attribute_name = "image";
    $disk = "public";
    $destination_path = "Genres";

    // if the image was erased
    if ($value == null) {
        // delete the image from disk
        \Storage::disk($disk)->delete($this->image);

        // set null in the database column
        $this->attributes[$attribute_name] = null;
    } // if a base64 was sent, store it in the db
    elseif (starts_with($value, 'data:image')) {
        // 0. Make the image
        $image = \Image::make($value);
        // 1. Generate a filename.
        $filename = md5($value . time()) . '.jpg';
        // 2. Store the image on disk.
        \Storage::disk($disk)->put($destination_path . '/' . $filename, $image->stream());
        // 3. Save the path to the database
        $this->attributes[$attribute_name] = $destination_path . '/' . $filename;
    } // else if a file was sent
    else {
        // 0. Convert the image to jpeg format
        $image = \Image::make($value)->encode('jpg', 100);
        // 1. Generate a filename
        $filename = md5($value . time()) . '.jpg';
        // 2. Store the image on disk
        \Storage::disk($disk)->put($destination_path . '/' . $filename, $image->stream());
        // 3. Save the path to databse
        $this->attributes[$attribute_name] = $destination_path . '/' . $filename;
    }
}