我在laravel 5.5中同步中间表时遇到了问题。
来自请求的帖子博客数据正在保存...但是在同步标签时我收到此错误:
"SQLSTATE[HY000]: General error: 1364 Field 'TagID' doesn't have a default value (SQL: insert into `blog_post_tag` (`PostID`) values (13))"
让我解释一下我有什么:
共有3个表:blog_posts,blog_tags,blog_post_tag(中间表)
在BlogPost模型中:
protected $table = 'blog_posts';
protected $primaryKey = 'PostID';
public function tags(){
return $this->belongsToMany('App\BlogTag', 'blog_post_tag', 'PostID', 'PostID');
}
和BlogTag模型:
protected $table = 'blog_tags';
protected $primaryKey = 'TagID';
// a tag can be found in multiple posts
public function posts(){
return $this->belongsToMany('App\BlogPost', 'blog_post_tag', 'TagID', 'TagID');
}
在BLogController中,我有一个保存或更新帖子的方法:
savePost方法:
// check if update or new
// validate data
// save the post - until here it`s ok
// syncronize tags - here comes the problems :)
if(isset($request->PostID) && $request->PostID != 0) {
// update post; check if the user delete all the tags for the current post
if(isset($request->tags)){
// without the true - which is default - is going to remove all the id`s and put it again
$post->tags()->sync($request->tags, true);
}
else
{
// it will remove all the associations (syncs) and is not gonna put anything!
$post->tags()->sync(array(), true);
}
} else {
// new post; use the sync method to sync the id`s in the blog_post_tag table
$post->tags()->sync($request->tags, false);
}
$ request->标签是一个带有选定标签的数组(TagsIDs):
<select class="form-control select2-multi" name="tags[]" multiple="multiple">
@foreach($tags as $tag)
<option value="{{ $tag->TagID }}">{{ $tag->Name }}</option>
@endforeach
</select>
我不明白我做错了什么?为什么抱怨'TagID'没有默认值。如果我没有发送任何标签,则没有错误。错误仅在更新或新帖子时出现。
答案 0 :(得分:0)
您在自定义表格上的键列名时遇到问题。
第三个参数是您所在模型的外键名称 正在定义关系,而第四个论点是 要加入的模型的外键名称
更新 BlogPost 模型
protected $table = 'blog_posts';
protected $primaryKey = 'PostID';
public function tags(){
return $this->belongsToMany('App\BlogTag', 'blog_post_tag', 'PostID', 'TagID');
}
BlogTag 型号:
protected $table = 'blog_tags';
protected $primaryKey = 'TagID';
// a tag can be found in multiple posts
public function posts(){
return $this->belongsToMany('App\BlogPost', 'blog_post_tag', 'TagID', 'PostID');
}
Laravel Doc
如果您对此有任何问题,请告诉我。