1

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?

2

This is called Eager Loading 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()
  • The fact that $responses-video was actually also an ElementCriteriaModel just came back to me and I've solved my problem by remembering that! But Eager Loading sounds like exactly what I need. Thanks. – foamcow Mar 6 '18 at 11:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.