Reputation: 11
i am new with laravel and I have a question while using polymorphic relationship.
Here is my simplified table structure :
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. polls and posts table have same column but some of it use different naming
My Poll model :
class Poll extends Model
{
/**
* Get all of the post's contents.
*/
public function contents()
{
return $this->morphMany('App\Models\Content', 'contentable');
}
}
My Post model :
class Post extends Model
{
/**
* Get all of the post's contents.
*/
public function contents()
{
return $this->morphMany('App\Models\Content', 'contentable');
}
}
My Content model :
class Content extends Model
{
/**
* Get all of the owning contentable models.
*/
public function contentable()
{
return $this->morphTo();
}
}
I want to retrieve all models from Content including Post and Poll, then create the list of it using foreach loop like this
$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
}
My question is,
Upvotes: 1
Views: 3226
Reputation: 1732
Add to your Content model
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);
}
And now you can this:
$contents = Content::with('contentable')->get();
foreach($contents as $content)
{
$name = $content->post->name;
//or $title = $content->poll->title
}
But, i dont understand why you need this relation, you can create one table(posts/polls) with this structure
id|name|category(post/poll)|created_at|updated_at
Upvotes: 1