【发布时间】:2019-01-04 05:10:49
【问题描述】:
所以我有一个posts 表和对应的Post 模型。我希望每个帖子都有相关的帖子。由于一个帖子可以有很多其他相关帖子,所以posts表和posts表(同一个表)之间是多对多的关系。
所以我创建了一个related_posts 数据透视表及其对应的模型RelatedPost。我想在两个模型中定义这种关系。像这样:
后模型:
public function related()
{
return $this->belongsToMany(RelatedPost::class, 'related_posts', 'related_id', 'post_id');
}
RelatedPost模型:
public function posts()
{
return $this->belongsToMany(Post::class, 'related_posts', 'post_id', 'related_id');
}
现在在我的帖子控制器中选择特定帖子后,我想获取其所有相关帖子。所以我这样做:
$post->related()->get();
但是当我这样做时,我收到以下错误消息:
"SQLSTATE[42000]: 语法错误或访问冲突: 1066 不是唯一的表/别名: 'related_posts' (SQL: select
related_posts.*,related_posts.related_idaspivot_related_id,related_posts.post_idaspivot_post_idfromrelated_postsinner joinrelated_postsonrelated_posts.id=related_posts.post_idwhererelated_posts.related_id= 1"
这是我对数据透视表的迁移:
Schema::create('related_posts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('post_id');
$table->unsignedInteger('related_id');
$table->timestamps();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->foreign('related_id')->references('id')->('posts')->onDelete('cascade');
});
我到处搜索,虽然我发现的解决方案真的很有意义,但我无法让它们中的任何一个起作用。
任何帮助将不胜感激!
【问题讨论】:
-
为什么要创建
RelatedPost模型?您的中间表不需要它。您的related()关系没有意义 - 它应该通过related_posts表指向Post模型。 -
@d3jn 非常感谢伙计。它现在正在工作。你为我节省了几个小时!
-
@AwaMelvine 你能在这里添加你的答案吗?
标签: laravel eloquent many-to-many laravel-5.6