【发布时间】: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 中检索所有模型,包括 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
}
我的问题是,
- 同时显示不同列的最佳方法是什么,例如 title 列或 name 列?
- 在这种情况下我可以使用列别名吗?所以我只是调用别名
【问题讨论】:
标签: php laravel eloquent polymorphism relationship