pro*_*pro 4 laravel eloquent laravel-5.8
嗨,我正在尝试将数据插入 db,但它说:
SQLSTATE [HY000]:常规错误:1364字段'标题'不具有默认值(SQL:插入到
projects(owner_id,updated_at,created_at)的值(1,2019年6月28日13点17分11秒,2019年6月28日13 :17:11))
控制器:
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');
}
Run Code Online (Sandbox Code Playgroud)
模型:
protected $guarded = [];
Run Code Online (Sandbox Code Playgroud)
桌子:
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');
});
Run Code Online (Sandbox Code Playgroud)
刀片文件:
<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>
Run Code Online (Sandbox Code Playgroud)
如何解决这个问题
您title在projects表上有该字段,但是您没有为其分配值。因为它设置为Not Nullable这将给出此错误。
$fillable在使用Project::create($attributes);您似乎没有的属性时,您将需要所有属性都在模型上的属性中。
的一个例子$fillable是:
protected $fillable = [
'title',
'description',
'owner_id',
];
Run Code Online (Sandbox Code Playgroud)
还有其他几个潜在的原因,但是如果不包括完整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');
}
Run Code Online (Sandbox Code Playgroud)
您可以ProjectRequest通过运行创建类php artisan make:request ProjectRequest,然后将验证规则放入其中。
在这里阅读更多。
| 归档时间: |
|
| 查看次数: |
7422 次 |
| 最近记录: |