Laravel 5.3 Creating Models Returns “Field doesn&#

2019-02-08 13:01发布

问题:

I'm using Laravel and Eloquent for two years and today I've decided to install a fresh Laravel 5.3 and try something with it.

I used an old database schema of mine and created my models, defined fillable columns. This is what my Page model looks like:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Page extends Model
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'language',
        'title',
        'slug',
        'url',
        'description',
        'tags',
        'wireframe',
        'order',
        'is_active'
    ];

    public function menus()
    {
        return $this->belongsToMany(Menu::class);
    }
}

url attribute is a TEXT-type column on MySQL so if I don't pass any value to it when creating a model, it should be a empty string. Instead, I keep getting SQLSTATE[HY000]: General error: 1364 Field 'url' doesn't have a default value error.

Here is my attempt to create a Post model:

Page::create([
    'title' => $root_menu['title'],
    'slug' => $root_menu['slug'],
    'language' => $this->language,
    'wireframe' => key(config('cms.wireframe')),
    'order' => 0
]);

Is this a Laravel 5.3 related issue or am I missing something? Thanks in advance for your helps.

回答1:

The reason for the error has been explained by @Nicklas.

The reason this is happening now, however, is that Laravel 5.3 uses strict mode for MySQL by default.

If you would like to revert to previous behavior, update your config/database.php file and set 'strict' => false for your connection.



回答2:

You are trying to insert an object, with no 'URL' attribute, into a table that has a 'URL' column without a default value. So the database can't know what to do with that column.

You can do one of three things.

  1. Fill in the URL value in the create
  2. Change your schema to allow null insertion on URL
  3. Change the URL schema to include a default value. (empty string)

Post your migration or schema, if you need further help.