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?

up vote 2 down vote accepted

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()

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.