gpt4 book ai didi

laravel - SQLSTATE [HY000] : General error: 1364 Field 'title' doesn't have a default value

转载 作者:行者123 更新时间:2023-12-03 19:44:34 29 4
gpt4 key购买 nike

嗨,我正在尝试将数据插入数据库,但它说:

SQLSTATE[HY000]: General error: 1364 Field 'title' doesn't have a default value (SQL: insert into projects (owner_id, updated_at, created_at) values (1, 2019-06-28 13:17:11, 2019-06-28 13:17:11))



我正在关注 Laracasts Laravel from scratch tutorial

Controller :
      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 = [];

table :
      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');
});

Blade 文件:
   <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>

如何解决这个问题

最佳答案

您有字段 titleprojects表但是您没有为其分配值。因为它被设置为 Not Nullable这将给出此错误。

您将需要所有属性都在 $fillable 中。使用 Project::create($attributes); 时模型上的属性你似乎没有。
$fillable 的一个例子将是 :

protected $fillable = [
'title',
'description',
'owner_id',
];

还有其他几个潜在的原因,但是如果不包括完整的 Project 就无法判断。模型和此请求来自的 View 。

编辑

您需要将您的功能更改为:
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然后将您的验证规则放在那里。

阅读更多 here .

关于laravel - SQLSTATE [HY000] : General error: 1364 Field 'title' doesn't have a default value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56807905/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com