Awa*_*ine 7 many-to-many laravel eloquent laravel-5.6
所以我有一个posts带有相应Post模型的表。我希望每个帖子都有相关帖子。由于一个帖子可以有很多其他相关的帖子,所以posts表和posts表(同一个表)之间是多对多的关系。
所以我创建了一个related_posts带有相应模型的数据透视表RelatedPost。我想在两个模型中定义这种关系。像这样:
岗位型号:
public function related()
{
return $this->belongsToMany(RelatedPost::class, 'related_posts', 'related_id', 'post_id');
}
Run Code Online (Sandbox Code Playgroud)
相关帖子模型:
public function posts()
{
return $this->belongsToMany(Post::class, 'related_posts', 'post_id', 'related_id');
}
Run Code Online (Sandbox Code Playgroud)
现在在我选择特定帖子后的帖子控制器中,我想获取其所有相关帖子。所以我这样做:
$post->related()->get();
Run Code Online (Sandbox Code Playgroud)
但是当我这样做时,我收到以下错误消息:
“SQLSTATE[42000]:语法错误或访问冲突:1066 不是唯一的表/别名:'related_posts'(SQL:select
related_posts.*,related_posts.related_idaspivot_related_id,related_posts.post_idaspivot_post_idfromrelated_postsinternal 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');
});
Run Code Online (Sandbox Code Playgroud)
我到处搜索,虽然我找到的解决方案确实很有意义,但我无法让它们中的任何一个工作。
任何帮助将不胜感激!
Awa*_*ine 10
感谢@d3jn 对我的问题的评论,我能够解决我的问题。所以我在这里发布解决方案,以防其他人可能需要它。
我将Post模型与其自身相关联,而不是与枢轴模型相关联RelatedPost。所以我不需要RelatedPost模型。我只需要一个数据透视表 ( related_post),以及关系的ids 即related_idand post_id。
因此,在迁移不变的情况下,我只需要取消RelatedPost模型并将模型中的related()方法更改Post为如下所示:
public function related()
{
return $this->belongsToMany(Post::class, 'related_posts', 'post_id', 'related_id');
}
Run Code Online (Sandbox Code Playgroud)
现在一切正常。
| 归档时间: |
|
| 查看次数: |
2830 次 |
| 最近记录: |