My goal is to order an element query of Matrix blocks by a custom field. Any thoughts?

namespace modules\mymodule\services;

use Craft;
use yii\base\Component;
use craft\elements\MatrixBlock;

class MyService extends Component
    public function myFunction()
        $blocks = MatrixBlock::find()

Edit to show working Example

(This is showing how I used this to sort by a custom date field)

$blocks = MatrixBlock::find()
    ->where(['>', 'content.field_blockType_fieldHandle', new \yii\db\Expression('NOW()')])
    ->orderBy(['content.field_blockType_fieldHandle' => SORT_ASC])


->orderBy(['fieldHandle' => SORT_DESC])

But you have to make sure the field is sortable, otherwise it won't work

  • Thanks for the reply! When you say "sortable" could you elaborate? For example, could I sort on a date time field? I've tried this exact code and I can get an error saying the field handle doesn't exist and in the query it doesn't look like craft is joining on the actual content table.
    – Peter Tell
    May 15 '18 at 16:21
  • Craft won't join the content table in MatrixQueries since Matrix blocks have their custom content tables. You'll have to use the exact column name $columnName = Craft::$app->getContent()->contentTable . '.' . Craft::$app->getContent()->fieldColumnPrefix . $field->handle; Only textual fields are sortable.. You can't sort relation fields or something like these May 15 '18 at 16:39
  • Oh, this looks like it's for an entry. What about a Matrix?
    – Peter Tell
    May 15 '18 at 17:19
  • If I put ->orderBy('craft_matrixcontent_mymatrixfield.field_blockType_fieldName') I get a DB exception
    – Peter Tell
    May 15 '18 at 17:26
  • Sry for the late reply. Did you specify a valid fieldId in your query? Otherwise it won't join the correct table and you'll have to do it on your own (I throught that was obvious sorry) May 16 '18 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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