laravel - SQLSTATE [HY000]:一般错误:1364 字段“标题”没有默认值
问题描述
您好我正在尝试将数据插入数据库,但它说:
SQLSTATE[HY000]: 一般错误: 1364 字段 'title' 没有默认值 (SQL: insert into
projects
(owner_id
,updated_at
,created_at
) 值 (1, 2019-06-28 13:17:11, 2019-06-28 13 :17:11))
我正在从头开始关注 Laracasts Laravel 教程
控制器:
public function store()
{
$attributes = $this->validateProject();
$attributes['owner_id'] = auth()->id();
$project = Project::create($attributes);
//Project::create($attributes);
//Project::create(request(['title', 'description']));
Mail::to($project->owner->email)->send(
new ProjectCreated($project)
);
return redirect('/projects');
}
模型:
protected $guarded = [];
桌子:
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('owner_id');
$table->string('title');
$table->text('description');
$table->timestamps();
$table->foreign('owner_id')->references('id')->on('users')->onDelete('cascade');
});
刀片文件:
<form method="POST" action="/projects">
@csrf
<div class="field">
<label class="label" for="title">Title</label>
<div class="control">
<input type="text" class="input {{ $errors->has('title') ? 'is-danger' : ''}}" name="title" value="{{ old('title') }}" placeholder="Project title">
</div>
</div>
<div class="field">
<label class="label" for="title">Description</label>
<div class="control">
<textarea name="description" class="textarea {{ $errors->has('description') ? 'is-danger' : ''}}" placeholder="Project description">{{ old('description') }}</textarea>
</div>
</div>
<div class="field">
<div class="control">
<button type="submit" class="button is-link">Create Project</button>
</div>
</div>
@include('errors')
</form>
如何解决这个问题
解决方案
title
您在表格上有该字段,projects
但是您没有为其分配值。因为它是这样设置的,Not Nullable
所以会出现这个错误。
使用时,您需要所有属性都在$fillable
模型的属性中,Project::create($attributes);
而您似乎没有。
的一个例子$fillable
是:
protected $fillable = [
'title',
'description',
'owner_id',
];
还有其他几个潜在的原因,但是如果没有您包括您的完整Project
模型和此请求来自的视图,就无法判断。
编辑
您需要将您的功能更改为:
public function store(ProjectRequest $request)
{
$attributes = $request->all();
$attributes['owner_id'] = auth()->id();
$project = Project::create($attributes);
Mail::to($project->owner->email)->send(
new ProjectCreated($project)
);
return redirect('/projects');
}
您可以ProjectRequest
通过运行php artisan make:request ProjectRequest
然后将验证规则放入其中来创建类。
在这里阅读更多。
推荐阅读
- java - 如何在 Visual Studio 代码中调试 Java 流?
- sql - 在 postgresql 上查询 Json 字段
- javascript - 当有多个文件类型时,材质 UI 输入不起作用
- iphone - 是否可以通过 GitHub iphone 应用程序分叉存储库?
- visual-studio-code - VSCode上下移动多行选择
- mysql - 带有 mysql 的 Spring Boot 应用程序卡在“Hikari-Pool-1 - 正在启动...”
- elasticsearch - Elasticsearch:自定义分析器中 synonym_graph 和停止过滤器之间的意外交互
- ssl - 如何使用 scapy 解密从 pcap 文件读取的 TLS 流量?
- salesforce-marketing-cloud - 我正在尝试过滤所有订阅者中的订阅者,以识别通过创建配置文件属性从哪个 MID 创建订阅者
- java - Java sftpChannel put error (系统找不到指定的路径)