繁体   English   中英

如何为一对多关系Laravel创建关联(在数据透视表中)?

[英]How to create association (in pivot table) for one to many relationship Laravel?

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

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']);
    });

创建$post$postVersion ,请尝试以下操作:

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

但这不起作用,并且我没有收到任何错误消息。 如何解决此问题并在PostPostVersion之间创建链接?

不像那样。 您应该创建2个表: postspost_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']));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM