Question:

How to get related entry data using ElementCriteriaModel in a plugin

Aaron: 2 weeks ago

I am working on a custom plugin which gets some entry data using

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->order('postDate asc');
$criteria->dateUpdated = array('and', '>=' . $this->dateFrom->format(DateTime::MYSQL_DATETIME), '<=' . $this->dateTo->format(DateTime::MYSQL_DATETIME));
$criteria->limit('null');

$responses = $criteria->find();

The returned entries contain a relationship to entries in another channel. In this case, the relationship field is named 'video'. So when looping through $responses I can see that $response->video is an array containing the sourceElement id and field id.

Is it possible to get the complete entry data for the related entry returned in the same query rather than needing to perform an additional query?

Answer:
Gianna: 2 weeks ago

This is called Eager Loading (https://craftcms.com/docs/templating/eager-loading-elements) you have to do

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->order('postDate asc');
$criteria->dateUpdated = array('and', '>=' . $this->dateFrom->format(DateTime::MYSQL_DATETIME), '<=' . $this->dateTo->format(DateTime::MYSQL_DATETIME));
$criteria->limit('null');

// ========== start change ===============
$criteria->with = ['video'];
// ========== end change  ================

$responses = $criteria->find();

Edit: One of the most important things when working with Craft.

I can see that $response->video is an array containing the sourceElement id and field id.

No, no and no. Many people believe this, or many other things, but that is not true. Your $response->video will contain an object of type ElementCriteriaModel. $respose->video is exactly the same type of object like $criteria = craft()->elements->getCriteria();

Thus you can do

$videos = $response->video->order('')->limit(2)->find()