【问题标题】:How can I get types of a morph in polymorphic many to many relationship in Laravel如何在 Laravel 中获取多态多对多关系中的变形类型
【发布时间】:2021-07-22 11:06:24
【问题描述】:

我有三张表 - 媒体、城市和流派。它们之间的关系是多对多(多态)。一个城市有许多媒体。一个流派也有许多媒体,反之亦然。

Cities
  id, name

Genres
  id, name

Medias
  id, name

Mediaable
  id, mediaable_id, mediaable_type

我想获取所有具有可媒体类型的媒体:

  #items: array:3 [▼
    0 => App\Models\Media {#1128 ▼
         [
       "id" => 1,
       'name'=>'foo.png',
       "types" => ['City', 'Genre']
  ],

   1 => App\Models\Media {#1128 ▼
        [
       "id" => 1,
       'name'=>'foo.png',
       "types" => ['City']
   ],

    2 => App\Models\Media {#1128 ▼
        [
       "id" => 1,
       'name'=>'foo.png',
       "types" => []
   ],
];

我该怎么做?

【问题讨论】:

  • 你已经尝试了什么?
  • @Elias 我不知道
  • 好吧,祝你好运:)
  • 这不是一个坏问题,但我需要澄清一个Media 是否可以有多个City 和多个Genre
  • 好的,所以下一个问题是:a) 你不知道如何从数据库中检索 Media 的关系,b) 是只想将 mediaable_types 作为类型返回而不返回完整关系的问题数据,或者 c) 你不知道怎么做?

标签: php laravel eloquent laravel-8


【解决方案1】:

假设您有一个 \App\Models\Medias::class 具有以下关系:

public function cities()
{
    return $this->morphToMany('Cities', 'mediaables');
}

public function genres()
{
    return $this->morphToMany('Genres', 'mediaables');
}

public function medias()
{
    return $this->morphByMany();
}

然后你可以使用以下内容:

public function getTypesAttribute(): string
{
    return $this->medias->each(function($media)
        {
            return class_basename($media);
        })
        ->unique() // Use this if you never want to besure you only get one City
        ->implode(', ');
}

如果您只想要基本的 Model 类名,那么您可以使用以下内容:

public function getTypesAttribute(): string
{
    return $this->medias->each(function($media)
        {
            return class_basename($media);
        })
        ->unique() // Use this to ensure City or Genre only appears once
        ->implode(', ');
}

如果您需要数据库中的城市名称和类型,那么我会使用以下内容:

public function getTypesAttribute(): string
{
    return $this->medias->pluck('name') // 'name' only works if every 'mediaable_type' model has a 'name' attribute
        ->unique() // Optional
        ->implode(', ');
}

这样,当您返回 API 数据时,您可以调用 use $media->types 来获取您需要的内容。

【讨论】:

    猜你喜欢
    • 2020-09-10
    • 2016-10-03
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    相关资源
    最近更新 更多