Laravel 5检索所有多态模型的最佳方法

时间:2018-07-10 09:25:48

标签: php laravel eloquent polymorphism relationship

我是laravel的新手,使用多态关系时我有一个疑问。

这是我的简化表结构:

polls
  id - integer
  name - string
  created_at - timestamp
  updated_at - timestamp

posts
  id - integer
  title - string
  created_at - timestamp
  updated_at - timestamp

contents
  id - integer
  contentable_id - integer
  contentable_type - string
  created_at - timestamp
  updated_at - timestamp

Ps。民意调查和职位表具有相同的列,但其中一些使用不同的命名

我的投票模型:

class Poll extends Model
{
    /**
     * Get all of the post's contents.
     */
    public function contents()
    {
        return $this->morphMany('App\Models\Content', 'contentable');
    }
}

我的帖子模型:

class Post extends Model
{
    /**
     * Get all of the post's contents.
     */
    public function contents()
    {
        return $this->morphMany('App\Models\Content', 'contentable');
    }
}

我的内容模型:

class Content extends Model
{
    /**
     * Get all of the owning contentable models.
     */
    public function contentable()
    {
        return $this->morphTo();
    }
}

我想从 Content 中检索所有模型,包括 Post Poll ,然后使用这样的foreach循环创建其列表

$contents = Content::with('contentable')->get();

foreach($contents as $content)
{
    $contentable = $content->contentable;

    //if its a poll then show title, created_at, and updated_at

    //or

    //if it's a post then show name, created_at, and updated_at 
}

我的问题是

  1. 显示不同列(例如同时显示标题列或名称列)的最佳方法是什么?
  2. 在这种情况下可以使用列别名吗?所以我只叫别名

1 个答案:

答案 0 :(得分:0)

添加到您的内容模型

public function post()
{
   return $this->hasOne(Post::class, 'id', 'contentable_id')
       ->where('contentable_type', Post::class);
}
public function poll()
{
   return $this->hasOne(Poll::class, 'id', 'contentable_id')
        ->where('contentable_type', Poll::class);
}

现在您可以:

$contents = Content::with('contentable')->get();

foreach($contents as $content)
{

      $name = $content->post->name;
      //or $title = $content->poll->title
}

但是,我不明白为什么需要这种关系,您可以使用这种结构创建一个表(帖子/民意测验)

id|name|category(post/poll)|created_at|updated_at
相关问题