Is there currently a way to eager load the matrix values of an element and thus be able to sort by one of its fields? Imagine you have something like the following:

$criteria = craft()->elements->getCriteria(ElementType::MatrixBlock);
$criteria->type = 'mytype';
$blocks = $criteria->find();

This would create a select from the following tables:

FROM   `craft_elements` `elements` 
   JOIN `craft_elements_i18n` `elements_i18n` 
     ON elements_i18n.elementid = elements.id 
   JOIN `craft_matrixblocks` `matrixblocks` 
     ON matrixblocks.id = elements.id 
   JOIN `craft_matrixblocktypes` `matrixblocktypes` 
     ON matrixblocktypes.id = matrixblocks.typeid 

Obviously the most important table for my task at hand is missing: the craft_matrixcontent_mytype table. I'm not able order by mytable.myfield and additionally, while looping those blocks I have the N+1 problem where it builds an extra query to fetch the actual block content.

Am I somehow able to load all MatrixBlocks of a given type, INCLUDING the values?

1 Answer 1


After digging through some code I found out, that the MatrixBlockElementType just returns a content table (which is necessary for the eager loading part), if a fieldId is given:

$criteria = craft()->elements->getCriteria(ElementType::MatrixBlock);
$criteria->type = 'mytype';
$criteria->fieldId = 90;
$criteria->order = 'field_mytype_myfield';

$blocks = $criteria->find();

Like this everything seems to work as expected and I'm again in love with crafts flexibility :)

Am I right that I have to pass in the id? I can't do it via the field handle 'mymatrixfieldhandle', correct?

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.