I'm trying to create an or query with 2 related fields and 1 title field. My version so far is this:

    ['relatedTo', 'targetElement' => $ids, 'field' => 'field1'],
    ['relatedTo', 'targetElement' => $ids, 'field' => 'field2'],
    ['like', 'title', $search]

But with that query I keep getting the error: Undefined array key 0

$ids is not empty.

Any suggestions?

2 Answers 2


I think relatedTo should not be used in that place, but should be used on the $searchQuery object instead:

    ['field' => 'field1', 'targetElement' => $ids],
    ['field' => 'field2', 'targetElement' => $ids],
  ->search('title:' ~ $search);

That being said, this would not give you the results that I think you're looking for (elements related to the $ids, OR with the title you searched for). To be honest, I don't think this can be done with one query, but maybe someone else knows the trick?

  • Yeah thanks for the reply but that solution is idd an AND not an OR. I used a workaround to get it to work. I posted it below.
    – bartpulse
    Commented Jun 16, 2023 at 10:59

Used an two step workaround by splitting it in 2 queries, merging the ids and searching by id in a 3rd query.

$searchUsersIds = User::find()->search($search['rawSearch'])->ids();

$searchUserResultIds = [];
if(!empty($searchUsersIds)) {
    $searchUserQuery =  clone $searchQuery;
            ['targetElement' => $searchUsersIds, 'field' => 'field1'],
            ['targetElement' => $searchUsersIds, 'field' => 'field2']

    $searchUserResultIds = $searchUserQuery->ids();

$searchCompanyQuery = clone $searchQuery;
$searchCompanyResultIds = $searchCompanyQuery->search($search['rawSearch'])->ids();

$companyEntryIds = array_merge($searchUserResultIds, $searchCompanyResultIds);

if(!empty($companyEntryIds)) {

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.