【问题标题】:Laravel 5 best approach to retrieve all polymorphic modelsLaravel 5 检索所有多态模型的最佳方法
【发布时间】:2018-12-18 02:07:03
【问题描述】:

我是 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

附言。 polls 和 posts 表具有相同的列,但其中一些使用不同的命名

我的投票模型:

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 中检索所有模型,包括 PostPoll,然后像这样使用 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. 同时显示不同列的最佳方法是什么,例如 title 列或 name 列?
  2. 在这种情况下我可以使用列别名吗?所以我只是调用别名

【问题讨论】:

    标签: php laravel eloquent polymorphism relationship


    【解决方案1】:

    添加到您的内容模型

    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
    

    【讨论】:

      猜你喜欢
      • 2017-04-01
      • 2019-01-03
      • 1970-01-01
      • 2019-11-14
      • 2015-08-29
      • 1970-01-01
      • 1970-01-01
      • 2017-10-11
      • 2017-04-09
      相关资源
      最近更新 更多