首页 > 解决方案 > 如何为一对多关系 Laravel 创建关联(在数据透视表中)?

问题描述

我正在尝试在两个模型之间创建链接,Post并且PostVersion. 我认为这个问题可能是由命名约定引起的,但我不确定。这些模型之间的关系定义如下:

Post

public function postVersion()
{
    return $this->hasMany(PostVersion::class);
}

PostVersion

public function post()
{
    return $this->belongsTo(Post::class);
}

我创建了一个名为的表PostPostVersion,其结构如下:

Schema::create('post_post_version', function (Blueprint $table) {
        $table->integer('post_id');
        $table->integer('post_version_id');
        $table->primary(['post_id', 'post_version_id']);
    });

在我创建了 a$post和 a之后$postVersion,我试试这个:

$post->postVersion()->associate($postVersion);

但它不起作用,我没有收到错误。我将如何解决这个问题并在Postand之间创建链接PostVersion

标签: phplaravelassociations

解决方案


不像那样。您应该创建 2 个表:posts&post_versions

posts表中:

Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    //
});

post_versions表中:

Schema::create('post_versions', function (Blueprint $table) {
    $table->unsignedInteger('post_id');
    $table->string('version');
    //
});

然后在创建帖子后:

$post->postVersion()->save(new App\Comment(['version' => 'v1.0.0']));

推荐阅读