timgavin
4 months ago

Trouble with defining relationships

Posted 4 months ago by timgavin

I'm having a hard time figuring out the relationships between my tags and posts.

I created a tagging system that would store tags in one table (tags) and the posts that use them in another (tags_posts).

What I want to do is get the tags when getting the posts by doing this: $post = Post::with('tags')->find(1); instead of something like this: $post = Post::with('tags.tags')->find(1);

So far all I've been able to do is get the tag IDs from the TagPost relationship and scratch my head a lot.

I tried a hasManyThrough relationship but that didn't work out too well. I'm kind of stuck here...

Schema::create('tags', function (Blueprint $table) {
    $table->increments('id');
    $table->string('slug')->unique();
    $table->string('name')->unique();
    $table->unsignedInteger('count')->default(0)->index();
    $table->timestamps();
});

Schema::create('tags_posts', function (Blueprint $table) {
    $table->unsignedInteger('tag_id')->index();
    $table->unsignedInteger('post_id')->index();
    $table->unique(['tag_id', 'post_id']);
});

Post.php

public function tags()
{
    return $this->hasMany(TagPost::class, 'post_id');
}

// tried this with no success
public function tags()
{
    return $this->hasManyThrough('App\Tag', 'App\TagPost', 'post_id', 'tag_id);
}

TagPost.php

public function tags()
{
    return $this->belongsToMany('App\Tag');
}

Hopefully this makes sense!

Please sign in or create an account to participate in this conversation.