1

How might I eager load category data in a plugin? I can't seem to figure out why I can't access a category in this way:

locationOffers is a matrix block name, category is the handle of a related category field inside of the matrix block

// this adds an empty category array to each related offer
$relatedOffers = $entry->locationOffers->with(['category'])->all(); 
print_R($relatedOffers->category); // is empty

// this regular way works, where I can access category->title, and more, 
// but is not eager loaded
$relatedOffers = $entry->locationOffers->all();

2 Answers 2

3

Apologies, I misread the question the first time around.

When eager loading via a matrix block, you need to provide a blocktype as well as the field name.

See: https://docs.craftcms.com/v3/dev/eager-loading-elements.html#eager-loading-elements-related-to-matrix-blocks for more details

1

You need to loop through the array returned by your element query

foreach ($relatedOffers as $offer) {
    print_r($offer->category);
}
1
  • The array is empty, so there's nothing to loop through.
    – jpea
    Oct 1, 2019 at 12:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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