Laravel属于ToMany在多个关系中在数据透视表id上插入'0'?

时间:2015-06-30 11:58:56

标签: php mysql laravel eloquent relational-database

我有以下架构:

objects

    Schema::create('objects', function(Blueprint $table) {
        $table->increments('object_id');
    });

关系为:

public function tags() {
    return $this->belongsToMany('Tag', 'objects_tags_pivot', '?', '?');
}

一个tags表:

    Schema::create('tags', function(Blueprint $table) {
        $table->increments('tag_id');
    });

关系为:

public function objects() {
    return $this->belongsToMany('Object', 'objects_tags_pivot', '?', '?');
}

他们之间的关系是多对多的关系:

    Schema::create('objects_tags_pivot', function(Blueprint $table) {
        $table->increments('object_tags_id');
        $table->integer('object_id')->unsigned();
        $table->integer('tag_id')->unsigned();
    });

我的问题是在目前有问号的关系参数中插入什么? Laravel 4.2文档建议第三个参数是$foreignKey,第四个参数是$localKey。这不是很有帮助。

每次尝试将object_idtag_id与这些参数匹配或将其留空都会导致数据透视表上的一个或多个字段为0。根本没用。

我应该在什么顺序指定每个参数?

1 个答案:

答案 0 :(得分:1)

Have you ever tried leaving them null? Laravel will already make foreign and local / other key assumptions based on the table name of the relation. For example, since the objects table model name is Object it will guess that the foreign key is named object_id. Also, since the tags model name is Tag, it will guess tag_id for the local / other key in a relationship.

If you want to fill them out manually, you need to insert the column names that indicate how the relationship is linked. For example:

public function tags()
{
     $this->belongsToMany('Tag', 'objects_tag_pivot', 'object_id', 'tag_id');
}