4

Is it possible to order and/or filter all entries from a section whose author has a custom field value that is set to "X"?

Below is the starting code.

in Twig:

{% set elementQuery = craft.entries()
    .section('sectionHandle')
    .with(['author'])
%}

in PHP:

$elementQuery = Entry::find()
    ->section('sectionHandle')
    ->with(['author']);
7

This requires a bit of extra work on the ElementQuery, but it can be efficiently done in the same query.

We first perform an inner join on the author's content table using the authorId so that the custom field is available to us.

in Twig:

{% set elementQuery = craft.entries()
    .section('sectionHandle')
    .with(['author'])
    .innerJoin('{{%content}} author_content', '[[author_content.elementId]] = [[authorId]]')
    .andWhere({'author_content.field_customFieldHandle': 'X'})
%}

in PHP:

$elementQuery = Entry::find()
    ->section('sectionHandle')
    ->with(['author'])
    ->innerJoin('{{%content}} author_content', '[[author_content.elementId]] = [[authorId]]')
    ->andWhere(['author_content.field_customFieldHandle' => 'X']);

To order by a custom field we use orderBy.

in Twig:

{% set elementQuery = craft.entries()
    .section('sectionHandle')
    .with(['author'])
    .innerJoin('{{%content}} author_content', '[[author_content.elementId]] = [[authorId]]')
    .orderBy('author_content.field_customFieldHandle asc')
%}

in PHP:

$elementQuery = Entry::find()
    ->section('sectionHandle')
    ->with(['author'])
    ->innerJoin('{{%content}} author_content', '[[author_content.elementId]] = [[authorId]]')
    ->orderBy('author_content.field_customFieldHandle asc');

To filter by a custom field we add andWhere.

in Twig:

{% set elementQuery = craft.entries()
    .section('sectionHandle')
    .with(['author'])
    .innerJoin('{{%content}} author_content', '[[author_content.elementId]] = [[authorId]]')
    .andWhere({'author_content.field_customFieldHandle': 'X'})
%}

in PHP:

$elementQuery = Entry::find()
    ->section('sectionHandle')
    ->with(['author'])
    ->innerJoin('{{%content}} author_content', '[[author_content.elementId]] = [[authorId]]')
    ->andWhere(['author_content.field_customFieldHandle' => 'X']);

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.