<p>If you have an EntryModel and know the category field's handle, you don't really need a service:</p>

<pre><code>$categories = $entry-&gt;categoryFieldHandle;
</code></pre>

<p>In other cases, you can construct an <a href="http://buildwithcraft.com/docs/templating/elementcriteriamodel" rel="nofollow">ElementCriteriaModel</a> to search for related elements (categories, entries, users or assets), using a number of different variables. Easy example to get related categories from an entry ID:</p>

<pre><code>$criteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Category);
$criteria-&gt;relatedTo = array($entryId);
$categories = craft()-&gt;elements-&gt;findElements($criteria);
</code></pre>

CC BY-SA 3.0
2015-05-28T07:25:53.557Z
Thank you mmikkel, I had come to a similar conclusion. I appreciate the second example, as that may come in handy later.  Is `craft()->elements->findElements($criteria)` different from `$criteria->find()` ?
kr37
CC BY-SA 3.0
2015-05-28T08:17:32.297Z
Not AFAIK – ```$criteria->find()``` actually calls ```craft()->elements->findElements()``` (which refers to the [ElementsService](https://buildwithcraft.com/classreference/services/ElementsService). Doesn't really matter which method you use, in my experience. ```$criteria->find()``` is shorter :)
Mats Mikkel Rummelhoff
CC BY-SA 3.0
2015-05-28T07:13:25.437Z
2015-05-28T07:13:25.437Z
Mats Mikkel Rummelhoff
<p>OK, here is what I worked out, through hours of trial and error. A hint came from the <a href="http://buildwithcraft.com/classreference/services/ElementsService" rel="nofollow">docs</a>:</p>

<blockquote>
  <p>This should be the starting point any time you want to fetch elements
  in Craft.</p>
  
  <p>$criteria = craft()->elements->getCriteria(ElementType::Entry);</p>
  
  <p>$criteria->section = 'news';</p>
  
  <p>$entries = $criteria->find();</p>
</blockquote>

<p>In my plugin's services file this produces the desired results:</p>

<pre><code>// Set up the criteria
$criteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Entry);
$criteria-&gt;section = 'events';
$criteria-&gt;startDate = array("&lt;=$toDateYmd", NULL);
$criteria-&gt;endDate = array("&gt;=$fromDateYmd", NULL);

$entries = $criteria-&gt;find();  //Do the query

foreach ($entries as $entry) {
    $categories = $entry-&gt;categories;
    echo "&lt;br&gt;title: $entry-&gt;title Start: $entry-&gt;startDate&lt;br&gt;&lt;pre&gt;";
    echo "Categories:&lt;/br&gt;";
    foreach ($categories as $k =&gt; $v) echo " [$k] =&gt; $v&lt;br&gt;";
}
</code></pre>

<p>When adding the criterias, each array is basically doing an 'OR'.  So it's 
<em>if startDate &lt;= $toDateYmd OR startdate = NULL</em>.  I just happen to need to accept NULL as a value here.</p>

<p>If anyone has a better way of doing it, please let me know, but code-wise this seems quite concise.</p>

CC BY-SA 3.0
2015-05-28T07:15:30.863Z
2015-05-28T07:15:30.863Z
kr37
<p>In a plugin, I've been advised to try to use craft built-in <a href="http://buildwithcraft.com/classreference#craft.app.services" rel="nofollow">services</a> instead of direct db queries. So can anyone help with this:  For an entry type that includes a categories field, how to get all the categories related to an entry?</p>

<p>I found this:</p>

<pre><code>$entry = craft()-&gt;entries-&gt;getEntryById($entryId);
</code></pre>

<p>So I suppose this might work as well:</p>

<pre><code>$category = craft()-&gt;categories-&gt;getCategoryById($categoryId);
</code></pre>

<p>But I can't find anything intelligible to me under the relations service. </p>

<p>Thanks for any help.</p>

<p>EDIT: On a related note, I see <a href="http://buildwithcraft.com/docs/templating/craft.entries" rel="nofollow">here</a> that in twig you can do this:</p>

<pre><code>{% for entry in craft.entries.section('news').limit(10) %}
&lt;article&gt;
    &lt;h1&gt;&lt;a href="{{ entry.url }}"&gt;{{ entry.title }}&lt;/a&gt;&lt;/h1&gt;
    {{ entry.summary }}
    &lt;a href="{{ entry.url }}"&gt;Continue reading&lt;/a&gt;
&lt;/article&gt;
{% endfor %}
</code></pre>

<p>Whereby Craft/Twig does all the work to find and return the 'summary' field related to each entry. Is there any php statement like this next confused one, following which I could get the categories related to each event?</p>

<pre><code>$events = craft()-&gt;entries.section('events').start('&lt;=$toDateYmd').end('OR', '&gt;=$fromDateYmd', '').status('publish');
foreach ($events as $event)
   $categories = $event.category;
</code></pre>

<p>Thank you!</p>

CC BY-SA 3.0
2015-05-27T23:55:28.193Z
I actually have a lot of questions about interacting with the database. The Craft documentation on [database queries](http://buildwithcraft.com/docs/plugins/database) is pretty sparse, mainly pointing to yiiframework.com which I find quite unintelligible. Any advice just for examples of db queries and updates at all?
kr37
<plugin-development><queries><services>
Using Services to get all the Categories related to an Entry?
# Using Services to get all the Categories related to an Entry?

(Asked by: username_0 on 2015-05-27)

In a plugin, I've been advised to try to use craft built-in services instead of direct db queries. So can anyone help with this:  For an entry type that includes a categories field, how to get all the categories related to an entry?
I found this:
$entry = craft()->entries->getEntryById($entryId);

So I suppose this might work as well:
$category = craft()->categories->getCategoryById($categoryId);

But I can't find anything intelligible to me under the relations service. 
Thanks for any help.
EDIT: On a related note, I see here that in twig you can do this:
{% for entry in craft.entries.section('news').limit(10) %}

    {{ entry.title }}
    {{ entry.summary }}
    Continue reading

{% endfor %}

Whereby Craft/Twig does all the work to find and return the 'summary' field related to each entry. Is there any php statement like this next confused one, following which I could get the categories related to each event?
$events = craft()->entries.section('events').start('<=$toDateYmd').end('OR', '>=$fromDateYmd', '').status('publish');
foreach ($events as $event)
   $categories = $event.category;

Thank you!

**Tags:** plugin-development, queries, services

> **Comments:**
> **username_0**: I actually have a lot of questions about interacting with the database. The Craft documentation on [database queries](http://buildwithcraft.com/docs/plugins/database) is pretty sparse, mainly pointing to yiiframework.com which I find quite unintelligible. Any advice just for examples of db queries and updates at all?  

---

## 2 answers

### Answer by username_1 on 2015-05-28. Score: 3 | Accepted answer

If you have an EntryModel and know the category field's handle, you don't really need a service:
$categories = $entry->categoryFieldHandle;

In other cases, you can construct an ElementCriteriaModel to search for related elements (categories, entries, users or assets), using a number of different variables. Easy example to get related categories from an entry ID:
$criteria = craft()->elements->getCriteria(ElementType::Category);
$criteria->relatedTo = array($entryId);
$categories = craft()->elements->findElements($criteria);

> **Comments:**
> **username_0**: Thank you mmikkel, I had come to a similar conclusion. I appreciate the second example, as that may come in handy later.  Is `craft()->elements->findElements($criteria)` different from `$criteria->find()` ?  
> **username_1**: Not AFAIK – ```$criteria->find()``` actually calls ```craft()->elements->findElements()``` (which refers to the [ElementsService](https://buildwithcraft.com/classreference/services/ElementsService). Doesn't really matter which method you use, in my experience. ```$criteria->find()``` is shorter :)  

---

### Answer by username_0 on 2015-05-28. Score: 1

OK, here is what I worked out, through hours of trial and error. A hint came from the docs:

This should be the starting point any time you want to fetch elements
  in Craft.
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'news';
$entries = $criteria->find();

In my plugin's services file this produces the desired results:
// Set up the criteria
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'events';
$criteria->startDate = array("<=$toDateYmd", NULL);
$criteria->endDate = array(">=$fromDateYmd", NULL);

$entries = $criteria->find();  //Do the query

foreach ($entries as $entry) {
    $categories = $entry->categories;
    echo "title: $entry->title Start: $entry->startDate";
    echo "Categories:";
    foreach ($categories as $k => $v) echo " [$k] => $v";
}

When adding the criterias, each array is basically doing an 'OR'.  So it's 
if startDate <= $toDateYmd OR startdate = NULL.  I just happen to need to accept NULL as a value here.
If anyone has a better way of doing it, please let me know, but code-wise this seems quite concise.


---

