3

I want to query some entries in a section.

I am able to write a query using a GET Param as a filter on the title field. If I want to query a custom field however I need to know the precise column otherwise craft yells at me.

How do I get to this information?

The following code is a very basic example of what I mean.

$request = Craft::$app->request;

$query = Entry::find()->section('profiles');
        
if($request->getParam('name')){
    $param = $request->getParam('name');
            
    $query->orWhere(['like', '`content`.`title`', $param]);
    $query->orWhere(['like', '`content`.`field_nationality_gkpaccfs`', $param]);
}

return $query->all();

Or is there a better alternative on how to query entries on multiple properties? I know that $query->title(...) would work, but I do not know how to chain multiple of those together using OR.

1 Answer 1

5

It's actually OK to hard code the complete field column name (i.e. field_nationality_gkpaccfs) – it won't change between environments, or if the field is resaved (unless you change the handle, of course).

If you don't want to do that, you can do this:

use craft\helpers\ElementHelper;

$nationalityField = Craft::$app->getFields()->getFieldByHandle('nationality');
$nationalityFieldColumn = ElementHelper::fieldColumnFromField($nationalityField);

...
$query->orWhere(['like', '`content`.`' . $nationalityFieldColumn . '`', $param]);
2
  • 1
    Thanks, this was exactly what I was looking for. It just seems wrong to write such a generated column name directly into the code, I much prefer using the ElementHelper Class. Commented Mar 24, 2022 at 7:47
  • Yeah I agree :) Commented Mar 24, 2022 at 8:07

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.