![](/img/trans.png)
[英]Laravel Voyager SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value
[英]SQLSTATE[HY000]: General error: 1364 Field 'mov_id' doesn't have a default value
有一个与电影和类别这两个表有关的问题
类别属于电影,这意味着我可以为电影设置多种类别。
所以在类别模型中,我将这段代码
public function movie(){
return $this->belongsTo('App\Movie', 'mov_id');
}
我要设置的category.mov_id = movie.id
在控制器部分,当我放空白时,验证很好,当然会显示错误消息。 但是问题是无法保存到数据库并且显示mov_id没有默认值
public function store(Request $request)
{
$rules = array(
'cat_title' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('category/create')
->withErrors($validator);
} else {
$movie = new Category();
$movie->cat_title = Input::get('cat_title');
$movie->save();
Session::flash('message', 'Successfully created!');
return Redirect::to('category');
}
}
最后,这是查看文件
<div class="table-container">
<form method="POST" action="{{ route('category.store') }}" role="form">
{{ csrf_field() }}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<input type="text" name="cat_title" id="cat_title" class="form-control input-sm" placeholder="分类">
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<input type="submit" value="Save" class="btn btn-success btn-block">
<a href="{{ route('category.index') }}" class="btn btn-info btn-block" >Back</a>
</div>
</div>
</form>
</div>
类别架构
Schema::create('category', function (Blueprint $table) {
$table->increments('id');
$table->string('cat_title');
$table->integer('mov_id');
$table->timestamps();
});
错误消息会告诉您确切的问题是什么。 您正在尝试插入类别记录,但是您的表单不包含mov_id
值。 您的架构指定mov_id
为整数,但不指定任何默认值,也不能为null。 因此,如果您不告知Laravel,则不知道将其用于mov_id
,因此它无法创建记录。
$table->integer('mov_id')->nullable();
但是我认为您将会遇到更大的问题。 一个类别可能根本不应该有电影ID-这意味着每个类别最多只能有1个电影。
我认为您真正想要的是电影和类别之间的多对多关系。 这意味着一部电影可以具有多个类别,并且一个类别可以分配给许多电影。
Laravel文档对此进行了很好的描述,并提供了一个示例 。 您需要更新您的Laravel关系:
// Category model
public function movie() {
return $this->belongsToMany('App\Movie');
}
// Movie model
public function category() {
return $this->belongsToMany('App\Category');
}
和您的架构:
Schema::create('movies', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
// ... etc
});
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('cat_title');
// ... etc
});
Schema::create('category_movie', function (Blueprint $table) {
$table->integer('category_id');
$table->integer('movie_id');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.