<p>I haven't tested it but it should give you a pretty good idea on how to set this up.</p>

<pre><code>public function actionTest() {
    $entryQuery = Entry::find()-&gt;section('mySection');

    // All the element relations. For example tags and categories.
    // These have to be Element objects. For example craft\elements\Tag.
    $myArrayWithTags = [/* ... */];
    $myArrayWithCategories = [/* ... */];
    $allRelations = array_merge($myArrayWithTags, $myArrayWithCategories);

    // Filter by relations
    $this-&gt;_applyRelationFilter($entryQuery, $allRelations);

    // Filter by custom fields
    $this-&gt;_applyFieldFilter($entryQuery, 'myRadioField', 'value2');
    $this-&gt;_applyFieldFilter($entryQuery, 'myNumberField', 3);
    $this-&gt;_applyFieldFilter($entryQuery, 'myCheckboxField', ['option1', 'option2']);

    // Build response string
    $content = "Entries:&lt;br&gt;";
    $content .= "&lt;pre&gt;" . json_encode($entryQuery-&gt;all()) . "&lt;/pre&gt;";

    // Respond
    $response = Craft::$app-&gt;getResponse();
    $response-&gt;content = $content;
    return $response;
}

private function _applyRelationFilter(ElementQuery $query, array $elements) : array {
    $relatedTo = [];

    // Build the list of relations in the correct format
    foreach($elements as $element) {
        array_push($relatedTo, [
            "targetElement" =&gt; $element
        ]);
    }

    // Create an array with and as the first value so 
    // the result only contains elements that have all the set relations
    $relatedTo = array_merge(['and'], $relatedTo);

    // Set query relatedTo
    return $query-&gt;relatedTo($relatedTo);
}

private function _applyFieldFilter(ElementQuery $query, string $handle, $value) {
    $query-&gt;andWhere([
        ('content.field_' . $handle) =&gt; $value
    ]);
}
</code></pre>

<p>You need to have the following imports:</p>

<pre><code>use Craft;
use craft\elements\Entry;
use craft\elements\db\ElementQuery;
</code></pre>

<p>Info about querying by custom field:
<a href="https://craftcms.stackexchange.com/a/22995/9754">https://craftcms.stackexchange.com/a/22995/9754</a></p>

CC BY-SA 4.0
2019-06-05T09:13:08.303Z
Thank you for your time. What goes in $myArrayWithTags,  handle of tag fields?
inrsaurabh
CC BY-SA 4.0
2019-06-05T09:21:05.277Z
@inrsaurabh The array should contain Elements. So in your case it would have to be filled with Tag objects (craft\element\Tag). Updated my answer :)
tim-pixeldeluxe
CC BY-SA 4.0
2019-06-05T09:28:09.507Z
Ok,

Currently, i am testing  `_applyRelationFilter` in this i am getting an error related to `ElementQuery`  which is `... instance of craft\elements\db\EntryQuery given ...`
inrsaurabh
CC BY-SA 4.0
2019-06-05T09:48:22.777Z
https://pastebin.com/i9jByDWd

Complete error when using `ElementQuery`
inrsaurabh
CC BY-SA 4.0
2019-06-05T09:58:19.130Z
@inrsaurabh You need to add the right imports. See my original answer for more details. Edited answer.
tim-pixeldeluxe
CC BY-SA 4.0
2019-06-05T09:59:42.913Z
That error is gone, actually, i was using `use craft\db\Query;`


if i call `$this->_applyFieldFilter($entryQuery, 'price', '100');` it gives me the result. but for checkbox field it wont return anything
inrsaurabh
CC BY-SA 4.0
2019-06-05T10:11:07.990Z
`_applyFieldFilter` it works for `radio and numbers` not for `checkbox`
inrsaurabh
CC BY-SA 4.0
2019-06-05T10:13:07.670Z
@inrsaurabh Try the updated code. Checkbox fields are stored as an array containing the values. Updated answer.
tim-pixeldeluxe
CC BY-SA 4.0
2019-06-05T10:20:40.817Z
I think you suggested like this
`$this->_applyFieldFilter($entryQuery, 'handle', ['value']);`

Here is the rawsql  https://pastebin.com/w9D4rrHq
inrsaurabh
CC BY-SA 4.0
2019-06-05T10:33:26.210Z
I checked fields in DB

Both have the same JSON format

`craft\fields\RadioButtons { "options":[{"label":"Ram","value":"ram","default":""}... ]}
craft\fields\Checkboxes  {"options":[{"label":"Open Floor Plan","value":"openFloorPlan","default":""} ...]}`
inrsaurabh
CC BY-SA 4.0
2019-06-05T11:36:26.667Z
@inrsaurabh Those are the field settings. The values are stored in the content table. Checkbox values are stored as an array. So in theory the code example above should work.
tim-pixeldeluxe
CC BY-SA 4.0
2019-06-05T11:59:31.387Z
Yes i checked that table in case of checkbox it stored in `[option1]`
inrsaurabh
CC BY-SA 4.0
2019-06-05T12:27:27.307Z
I addedd like , and it works.

`private function _applyFieldFilter(ElementQuery $query, string $handle, $value) {
      $query->andWhere([
          'like', ('content.field_' . $handle), $value
      ]);
    }`
inrsaurabh
CC BY-SA 4.0
2019-06-05T09:06:21.393Z
2019-06-05T10:11:44.100Z
2019-06-05T10:11:44.100Z
tim-pixeldeluxe
<p>I am trying to get the entries based on multiple fields.
Fields can be of type tags, checkbox, radio box, and number.</p>

<p>In my controller currently what I tried is.</p>

<p><code>$extrafilter</code> will be like</p>

<pre><code>Array
(
    [0] =&gt; Array // other field
        (
            [handle] =&gt; amenities
            [value] =&gt; laundry
        )

    [1] =&gt; Array // tag field
        (
            [handle] =&gt; technologies
            [value] =&gt; 45
        )

)
</code></pre>

<p>Code to narrow down the result.</p>

<pre><code>use Craft;
use craft\elements\Entry;
use craft\elements\db\ElementQuery;

$entryQuery = Entry::find();
$entryQuery-&gt;section($sectionName);

if ($extrafilter &amp;&amp; !empty($extrafilter[0])) {
  $relatedTo = [];
  $fieldList = [];

  foreach ($extrafilter as $key =&gt; $value) {
     $relatedTo[] = $value['value'];
     $fieldList[] = $value['handle'];
  }

  $entryQuery-&gt;relatedTo = array(
        'targetElement' =&gt; array_merge(['and'], $relatedTo),
        'field' =&gt; $fieldList,
  );
}
$entries = $entryQuery-&gt;all();
</code></pre>

<p>This works for Tags but for other fields it dont give any result.</p>

<p>I checked these Questions </p>

<ol>
<li><a href="https://craftcms.stackexchange.com/questions/17990/display-entries-that-meet-multiple-tag-params">Display entries that meet multiple tag params</a></li>
</ol>

<plugin-development><craft3><controller><relatedto>
Get entries based on multiple fields in controller
# Get entries based on multiple fields in controller

(Asked by: username_0 on 2019-06-05)

I am trying to get the entries based on multiple fields.
Fields can be of type tags, checkbox, radio box, and number.
In my controller currently what I tried is.
$extrafilter will be like
Array
(
    [0] => Array // other field
        (
            [handle] => amenities
            [value] => laundry
        )

    [1] => Array // tag field
        (
            [handle] => technologies
            [value] => 45
        )

)

Code to narrow down the result.
use Craft;
use craft\elements\Entry;
use craft\elements\db\ElementQuery;

$entryQuery = Entry::find();
$entryQuery->section($sectionName);

if ($extrafilter && !empty($extrafilter[0])) {
  $relatedTo = [];
  $fieldList = [];

  foreach ($extrafilter as $key => $value) {
     $relatedTo[] = $value['value'];
     $fieldList[] = $value['handle'];
  }

  $entryQuery->relatedTo = array(
        'targetElement' => array_merge(['and'], $relatedTo),
        'field' => $fieldList,
  );
}
$entries = $entryQuery->all();

This works for Tags but for other fields it dont give any result.
I checked these Questions 

Display entries that meet multiple tag params

**Tags:** plugin-development, craft3, controller, relatedto

---

## 1 answers

### Answer by username_1 on 2019-06-05. Score: 3

I haven't tested it but it should give you a pretty good idea on how to set this up.
public function actionTest() {
    $entryQuery = Entry::find()->section('mySection');

    // All the element relations. For example tags and categories.
    // These have to be Element objects. For example craft\elements\Tag.
    $myArrayWithTags = [/* ... */];
    $myArrayWithCategories = [/* ... */];
    $allRelations = array_merge($myArrayWithTags, $myArrayWithCategories);

    // Filter by relations
    $this->_applyRelationFilter($entryQuery, $allRelations);

    // Filter by custom fields
    $this->_applyFieldFilter($entryQuery, 'myRadioField', 'value2');
    $this->_applyFieldFilter($entryQuery, 'myNumberField', 3);
    $this->_applyFieldFilter($entryQuery, 'myCheckboxField', ['option1', 'option2']);

    // Build response string
    $content = "Entries:";
    $content .= "" . json_encode($entryQuery->all()) . "";

    // Respond
    $response = Craft::$app->getResponse();
    $response->content = $content;
    return $response;
}

private function _applyRelationFilter(ElementQuery $query, array $elements) : array {
    $relatedTo = [];

    // Build the list of relations in the correct format
    foreach($elements as $element) {
        array_push($relatedTo, [
            "targetElement" => $element
        ]);
    }

    // Create an array with and as the first value so 
    // the result only contains elements that have all the set relations
    $relatedTo = array_merge(['and'], $relatedTo);

    // Set query relatedTo
    return $query->relatedTo($relatedTo);
}

private function _applyFieldFilter(ElementQuery $query, string $handle, $value) {
    $query->andWhere([
        ('content.field_' . $handle) => $value
    ]);
}

You need to have the following imports:
use Craft;
use craft\elements\Entry;
use craft\elements\db\ElementQuery;

Info about querying by custom field:
https://craftcms.stackexchange.com/a/22995/9754

> **Comments:**
> **username_0**: Thank you for your time. What goes in $myArrayWithTags,  handle of tag fields?  
> **username_1**: @inrsaurabh The array should contain Elements. So in your case it would have to be filled with Tag objects (craft\element\Tag). Updated my answer :)  
> **username_0**: Ok,  Currently, i am testing  `_applyRelationFilter` in this i am getting an error related to `ElementQuery`  which is `... instance of craft\elements\db\EntryQuery given ...`  
> **username_0**: https://pastebin.com/i9jByDWd  Complete error when using `ElementQuery`  
> **username_1**: @inrsaurabh You need to add the right imports. See my original answer for more details. Edited answer.  
> **username_0**: That error is gone, actually, i was using `use craft\db\Query;`   if i call `$this->_applyFieldFilter($entryQuery, 'price', '100');` it gives me the result. but for checkbox field it wont return anything  
> **username_0**: `_applyFieldFilter` it works for `radio and numbers` not for `checkbox`  
> **username_1**: @inrsaurabh Try the updated code. Checkbox fields are stored as an array containing the values. Updated answer.  
> **username_0**: I think you suggested like this `$this->_applyFieldFilter($entryQuery, 'handle', ['value']);`  Here is the rawsql  https://pastebin.com/w9D4rrHq  
> **username_0**: I checked fields in DB  Both have the same JSON format  `craft\fields\RadioButtons { "options":[{"label":"Ram","value":"ram","default":""}... ]} craft\fields\Checkboxes  {"options":[{"label":"Open Floor Plan","value":"openFloorPlan","default":""} ...]}`  
> **username_1**: @inrsaurabh Those are the field settings. The values are stored in the content table. Checkbox values are stored as an array. So in theory the code example above should work.  
> **username_0**: Yes i checked that table in case of checkbox it stored in `[option1]`  
> **username_0**: I addedd like , and it works.  `private function _applyFieldFilter(ElementQuery $query, string $handle, $value) {       $query->andWhere([           'like', ('content.field_' . $handle), $value       ]);     }`  

---

