Home > database >  retrieve Many to Many ( Poplymorphic )
retrieve Many to Many ( Poplymorphic )

Time:05-22

I would like to deep dive a little bit in many to many polymorphic, I have this structure :

posts
    id - integer
    name - string

videos
    id - integer
    name - string

tags
    id - integer
    name - string

taggables
    tag_id - integer
    taggable_id - integer
    taggable_type - string

I would like to get tags.name and posts.name where tags.id = 1 for example, I would like to get an array like that :

[
   'posts.name'   =>  'tags.name'
]

My Models :

<?php

     namespace App\Models;

     use Illuminate\Database\Eloquent\Model;

     class Post extends Model
      {
     /**
      * Get all of the tags for the post.
      */
      public function tags()
      {
         return $this->morphToMany(Tag::class, 'taggable');
      }
  }

 <?php

     namespace App\Models;

     use Illuminate\Database\Eloquent\Model;

     class Tag extends Model
      {
      /**
        * Get all of the posts that are assigned this tag.
      */
      public function posts()
      {
        return $this->morphedByMany(Post::class, 'taggable');
      }

      /**
        * Get all of the videos that are assigned this tag.
       */
      public function videos()
      {
         return $this->morphedByMany(Video::class, 'taggable');
      }
    }

I would like to get the post name and its tags in an array

CodePudding user response:

have you tried,

Post::with('tags')->get(/* YOUR FIELDS of choice */)->toArray();

  • Related