检索多对多(多态)

retrieve Many to Many ( Poplymorphic )

我想深入了解多对多多态,我有这个结构:

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

我想得到 tags.name 和 posts.name,其中 tags.id = 1 例如,我想得到这样的数组:

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

我的模特:

<?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');
      }
    }

我想在数组中获取 post 名称及其标签

你试过了吗,

Post::with('tags')->get(/* 你选择的字段 */)->toArray();