Web Development

With Relational ActiveRecord implementations, it is very common to retrieve records from relationships:

$criteria = new CDbCriteria();
$criteria->condition = 't.slug=:slug';
$criteria->params = array(':slug'=>$_GET['slug']);

$category = Category::model()->find($criteria);

// Retrieve Deals of a Category
$deals = $category->deals //array

Scoped Relations

Sometimes you want to retrieve relations that have a scope . In the Yii Framework, you can do the following:

$criteria = new CDbCriteria();
$criteria->condition = 't.slug=:slug';
$criteria->params = array(':slug'=>$_GET['slug']);

$category = Category::model()->find($criteria);

$criteria = new CDbCriteria();
$criteria->condition = 't.category_id=:category_id';
$criteria->params = array(':category_id'=>$category->id);

// Retrieve Deals with a 'published' scope
$deals = Deal::model()->published()->findAll();

A Better Way

$criteria = new CDbCriteria();
$criteria->condition = 't.slug=:slug';
$criteria->params = array(':slug'=>$_GET['slug']);

$category = Category::model()->find($criteria);

// Retrieve Deals with a 'published' scope
$deals = $category->deals(array('scopes' => array('published')));

Using Eager Loading

$criteria = new CDbCriteria();
$criteria->condition = 't.slug=:slug';
$criteria->params = array(':slug'=>$_GET['slug']);
$criteria->with = array('deals:published:by_latest');

$category = Category::model()->find($criteria);

Awesome!