[英]create hasMany or one to many relationship from a pivot table - Laravel
[英]How to create association (in pivot table) for one to many relationship 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']);
});
创建$post
和$postVersion
,请尝试以下操作:
$post->postVersion()->associate($postVersion);
但这不起作用,并且我没有收到任何错误消息。 如何解决此问题并在Post
和PostVersion
之间创建链接?
不像那样。 您应该创建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']));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.