2

I need to arbitrarily query entries based on the values of various fields.

For example, if I have an entry type called "Widgets" I can grab them like this:

$widgets = Entry::find()->section('widget')->all();

Now what if widgets have a field called "widgetColor" and I want to select all with a value of "blue" in that field?

  1. How can I query for those entries?
  2. Also, how can I query for any entry with no value in that field?

I've tried my best to figure it out using the documentation and it seems like method such as where only apply to certain data, such as the title and slug, which are not custom fields on the entry type.

Thanks!

5

You can do the same like with the section, if the query param exists in the field layout

$widgets = Entry::find()->widgetColor('blue')->text(':notempty:')->anotherField(':empty:')->section('widget')->all();

Will search for entries where widgetColor is blue, text is not empty/null and anotherField is empty/null

Edit: just for people who like to understand the behavior

Just to explain you the where parameter in the ElementQuery. The where function uses the Yii2 Query function directly and works directly at the database layer. When you take a look at your content table you'll see all custom fields have a certain prefix (if you didn't change it) so your widgetColor column will look like field_widgetColor when you do

where->(['widgetColor' => 'blue');

it will query

where `content`.`widgetColor` = `blue`

which will throw an error since the column name is field_widgetColor. The __set function in the Yii/component/ QueryBuilder class will set magic property that exists because of the field handle in your field layout... Or to keep it simple: you can access any "magic" property with the same name like an existing field handle.

Doing

->widgetColor($property)

will call the __set function that calls a wrapper that will wrap/attach the field content prefix (field_) to the where function. Thus you can use

where->(['field_widgetColor' => 'blue');

or

where->([Craft::$app->getFields()->oldFieldColumnPrefix . 'widgetColor' => 'blue');

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.