sync intermediate table in laravel error: Field doesn't have a default value

sync intermediate table in laravel error: Field doesn't have a default value

我在同步 laravel 5.5 中的中间 table 时遇到问题。

来自请求的 post 博客数据正在保存...但是当同步标签时我得到这个错误:

"SQLSTATE[HY000]: General error: 1364 Field 'TagID' doesn't have a default value (SQL: insert into `blog_post_tag` (`PostID`) values (13))"

让我解释一下我有什么:

有3个table:blog_posts、blog_tags、blog_post_tag(中间table)

在 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 中,我有一种方法可以保存或更新 post:

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->tags 是一个包含选定标签(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' 没有默认值。如果我不发送任何标签,则没有错误。错误仅在更新或新 post.

时出现

您确实在 table 上自定义键的列名时遇到问题。

The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to

更新您的 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

如果您对此有任何问题,请告诉我..