Laravel 5.3 创建模型返回“字段没有默认值”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39301589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5.3 Creating Models Returns "Field doesn't have a default value"
提问by Guney Cobanoglu
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.
我使用 Laravel 和 Eloquent 两年了,今天我决定安装一个新的 Laravel 5.3 并尝试使用它。
I used an old database schema of mine and created my models, defined fillable columns. This is what my Page
model looks like:
我使用了我的旧数据库模式并创建了我的模型,定义了可填充的列。这是我的Page
模型的样子:
<?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.
url
属性是TEXT
MySQL 上的一个-type 列,所以如果我在创建模型时没有向它传递任何值,它应该是一个空字符串。相反,我不断收到SQLSTATE[HY000]: General error: 1364 Field 'url' doesn't have a default value
错误。
Here is my attempt to create a Post model:
这是我创建 Post 模型的尝试:
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.
这是 Laravel 5.3 相关问题还是我遗漏了什么?预先感谢您的帮助。
回答by patricus
The reason for the error has been explained by @Nicklas.
@Nicklas 已经解释了错误的原因。
The reason this is happening now, however, is that Laravel 5.3 uses strict
mode for MySQL by default.
然而,现在发生这种情况的原因是 Laravel 5.3strict
默认使用MySQL 模式。
If you would like to revert to previous behavior, update your config/database.php
file and set 'strict' => false
for your connection.
如果您想恢复到以前的行为,请更新您的config/database.php
文件并设置'strict' => false
为您的连接。
回答by Nicklas Kevin Frank
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.
您正在尝试将没有“URL”属性的对象插入到具有“URL”列但没有默认值的表中。所以数据库无法知道如何处理该列。
You can do one of three things.
你可以做三件事之一。
- Fill in the URL value in the create
- Change your schema to allow null insertion on URL
- Change the URL schema to include a default value. (empty string)
- 在创建中填写 URL 值
- 更改架构以允许在 URL 上插入空值
- 更改 URL 架构以包含默认值。(空字符串)
Post your migration or schema, if you need further help.
如果您需要进一步的帮助,请发布您的迁移或架构。