
Quicktip: How to display morphTo relation into list columns
The use case
When using a morphTo
relationship type in WinterCMS, you can't display the relation data inside the columns of a ListController
, that is not supported yet:
// models/ForumDiscussion.php
public $morphTo = [
'author' => []
];
// models//forumdiscussion/columns.yaml
author_name:
label: Author name
relation: author
select: name
The work around
A simple workaround which will work for most of the cases is to use an accessor:
// models/ForumDiscussion.php
public $morphTo = [
'author' => []
];
public function getAuthorNameAttribute()
{
return $this->author->name;
}
// models//forumdiscussion/columns.yaml
author_name:
label: Author name
Additionally, to avoid n+1 issue, you should add into the listExtendQuery
method of the controller the relation eager-load:
// controllers/ForumDiscussions.php
public function listExtendQuery($query)
{
return $query->with('author');
}
More WinterCMS' tips
You want more WinterCMS' tips? Follow me on Twitter!
Comments
Be the first to post a comment!