<p>You're using <code>$criteria</code>, but attempting to set the <code>relatedTo</code> property on <code>$this-&gt;criteria</code>.</p>

<p>Assuming that's not the issue, have you tried using <code>$criteria-&gt;setAttribute('relatedTo', ['targetElement' =&gt; $category])</code>?</p>

<p>I've found <code>setAttribute</code> to be more reliable than the <code>ElementCriteriaModel</code> magic methods.</p>

CC BY-SA 3.0
2017-03-13T23:37:45.110Z
2017-03-13T23:37:45.110Z
Stephen Lewis
<p>I'm trying to extend the ElementCriteriaModel using the guide here:</p>

<p><a href="https://blog.tighten.co/craft-cms-building-complex-queries-by-extending-the-elementcriteriamodel" rel="nofollow noreferrer">https://blog.tighten.co/craft-cms-building-complex-queries-by-extending-the-elementcriteriamodel</a> </p>

<p>However I need to re-implement <code>relatedTo</code> keyword somehow. This is what I have so far but doesn't seem to work at all</p>

<pre><code>    $criteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Category);
    $criteria-&gt;slug = 'seasonal-event';
    $criteria-&gt;limit = 1;

    $category = $criteria-&gt;find();

    $this-&gt;criteria-&gt;relatedTo = array(
        'targetElement' =&gt; $category
    );

    return $this;
</code></pre>

CC BY-SA 3.0
2017-03-13T19:09:18.627Z
Any errors thrown?
Krzysztof Boduch
<plugin-development><entries><elementtype><queries>
Using relatedTo programatically?
# Using relatedTo programatically?

(Asked by: username_0 on 2017-03-13)

I'm trying to extend the ElementCriteriaModel using the guide here:
https://blog.tighten.co/craft-cms-building-complex-queries-by-extending-the-elementcriteriamodel 
However I need to re-implement relatedTo keyword somehow. This is what I have so far but doesn't seem to work at all
    $criteria = craft()->elements->getCriteria(ElementType::Category);
    $criteria->slug = 'seasonal-event';
    $criteria->limit = 1;

    $category = $criteria->find();

    $this->criteria->relatedTo = array(
        'targetElement' => $category
    );

    return $this;

**Tags:** plugin-development, entries, elementtype, queries

> **Comments:**
> **username_1**: Any errors thrown?  

---

## 1 answers

### Answer by username_2 on 2017-03-13. Score: 3

You're using `$criteria`, but attempting to set the `relatedTo` property on `$this->criteria`.

Assuming that's not the issue, have you tried using `$criteria->setAttribute('relatedTo', ['targetElement' => $category])`?

I've found `setAttribute` to be more reliable than the `ElementCriteriaModel` magic methods.


---

