So I have a posts
table with a corresponding Post
model. I want to have related posts for every post. Since a post can have many other related posts, it is a many-to-many relationship between the posts
table and the posts
table (same table).
So I created a related_posts
pivot table with its corresponding model RelatedPost
. I want to define this relationship in the two models. Like so:
Post model:
public function related()
{
return $this->belongsToMany(RelatedPost::class, 'related_posts', 'related_id', 'post_id');
}
RelatedPost model:
public function posts()
{
return $this->belongsToMany(Post::class, 'related_posts', 'post_id', 'related_id');
}
Now in my post controller after selecting a particular post, I want to get all its related posts. So I do this:
$post->related()->get();
But when I do this I get the following error message:
"SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'related_posts' (SQL: select
related_posts
.*,related_posts
.related_id
aspivot_related_id
,related_posts
.post_id
aspivot_post_id
fromrelated_posts
inner joinrelated_posts
onrelated_posts
.id
=related_posts
.post_id
whererelated_posts
.related_id
= 1) "
This is my migration for the pivot table:
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');
});
I have searched all over everywhere and though the solutions I've found really make sense I haven't been able to get any of them to work.
Any help will be very much appreciated!