Ad

Laravel 6.9 BelongsToMany Relationships Return One Collection

- 1 answer

I have Many To Many Relationships. I have three tables:

posts
posts_tag
tags

Table "posts" have standart fields.

The structure of the table "posts_tag":

Schema::create('post_tag', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->bigInteger('post_id')->unsigned();
    $table->foreign('post_id')->references('id')->on('posts');

    $table->bigInteger('tag_id')->unsigned();
    $table->foreign('tag_id')->references('id')->on('tags');
});

The structure of the table "tags":

Schema::create('tags', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->timestamps();
});

The relationship is defined in the model:

 class Tag extends Model
{

        public function posts()
    {
        return $this->belongsToMany(Post::class,'post_tag', 'post_id', 'tag_id');
    }
}

I call the method $tag->posts:

public function getPostsByTag($id)
{
    $tag = Tag::find($id);

    dd($tag->posts);

}

I get only one array:

Illuminate\Database\Eloquent\Collection {#571 ▼
  #items: array:1 [▶]
}

screenshot database

I will be grateful for any help friends! If you're sorry for my English, I'm in the process of learning!

Ad

Answer

In your Tag modal

class Tag extends Model
{
    public function posts()
    {
        return $this->belongsToMany(Post::class,'post_tag', 'post_id', 'tag_id');
    }
}

In your Post modal

class Post extends Model
{
    public function tags()
    {
        return $this->belongsToMany(Tag::class,'post_tag', 'tag_id', 'post_id');
    }
}

In your controller

public function getPostsByTag($id)
{
    $tag = Post::with('tags')->find($id);
    dd($tag);
}
Ad
source: stackoverflow.com
Ad