【问题标题】:Laravel defining a many-to-many relationship with the same tableLaravel 定义同一张表的多对多关系
【发布时间】: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_id as pivot_related_id, related_posts .post_id as pivot_post_id from related_posts inner join related_posts on related_posts.id = related_posts.post_id where related_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


【解决方案1】:

感谢@d3jn 对我的问题的评论,我能够解决我的问题。所以我在这里发布解决方案以防其他人可能需要它。

我将Post 模型与其自身相关联,而不是与枢轴模型RelatedPost 相关联。所以我不需要RelatedPost 模型。我只需要一个数据透视表(related_post)和关系的ids 即related_idpost_id

因此,在我的迁移不变的情况下,我只需要取消 RelatedPost 模型并将 Post 模型中的 related() 方法更改为如下所示:

public function related()
{
  return $this->belongsToMany(Post::class, 'related_posts', 'post_id', 'related_id');
}

现在一切正常。

【讨论】:

    猜你喜欢
    • 2019-10-15
    • 2013-02-17
    • 2012-08-27
    • 2020-09-09
    • 2012-11-17
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多