douchao0358 2017-12-26 23:05
浏览 58

HasManyThrough Polymorphic model或morphto没有中介?

Consider the following Eloquent docs polymorphic example as a starting point: (https://laravel.com/docs/5.5/eloquent-relationships#polymorphic-relations)

In this variation, it's a bit of a reverse direction. User hasMany Medias. Medias are polymorphic and can be any model.

Goal is to be able to query User->media relation and return the corresponding post and video models.

Issue: Currently the only way I can get the post or video models, is query the mediable relation: User->media->mediable. In order to map the polymorphic models, we need the medias table where the media_id and media_type are recorded.

A HasManyThrough relation seems like the logical solution, but appears to be constrained by having to know the desired model type.

Is there a way to achieve my desired results?

DB:

user
    id

posts
    id - integer
    title - string
    body - text

videos
    id - integer
    title - string
    url - string

medias
    id - integer
    user_id - integer
    media_id - integer
    media_type - string

Models:

class User
  public function media()
  {
      return $this->hasMany('App\Media');
  }

class Media
  public function mediable()
  {
      return $this->morphTo();
  }

class Post
  public function Media()
  {
      return $this->morphMany('App\Media', 'mediable');
  }

class Videos
  public function Media()
  {
      return $this->morphMany('App\Media', 'mediable');
  }
  • 写回答

0条回答 默认 最新

    报告相同问题?