首页 > 解决方案 > 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>

如何解决这个问题

标签: laraveleloquentlaravel-5.8

解决方案


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然后将验证规则放入其中来创建类。

在这里阅读更多。


推荐阅读