php - 如何为一对多关系 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);
但它不起作用,我没有收到错误。我将如何解决这个问题并在Post
and之间创建链接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']));
推荐阅读
- lambda - 语言级别 7 不支持 android studio lambda 表达式
- javascript - 无法从客户端调用链代码:处理事务时出错。错误:需要 PEM 编码证书
- css - 如何制作一个矩形透明度渐变CSS3?
- javascript - 如何为一组 CSS 样式设置 :before psudo 属性
- sql-server - SQL server - 在 where 子句中使用聚合的替代方法
- javascript - d3.js Hierarchical Edge Bundling 动态数据
- python - PyTorch - 通过 ImageFolder 加载数据时如何使用 k 折交叉验证?
- delphi - 我的 Delphi 安装不提供 REST 客户端模块,即使在创建 Datasnap REST 服务器之后也是如此
- html - 接下来对齐导航栏下拉项
- android - 如何通过滚动仅显示微调器中的前 3 个项目和其他项目?