In Craft 3, I want to list all the categories in a group and all the entries related to them. How can I do this?
1 Answer
The slower but easier approach is to fetch all of them and search for related entries
'elementType' => Category::class,
'criteria' => [
'group' => 'yourGroup',
],
'paginate' => false,
'transformer' => function(Category $category) {
$entries = Entry::find()
->relatedTo($category)
->select(['title'])
->asArray()
->column();
return [
'title' => $category->title,
'entries' => $entries
];
}
Learn more about Element Queries especially the different ways to fetch entries via one(), all(), column()