So just to answer my own question should anyone need this.
I’m building a one-liner call for an API to get all posts, get the associated comments with each post and get the photo and name of the user who added the comment. It has to be an eager query so we minimize the database calls and return all information to the API it requires in one call.
User model has an ‘api’ scope saying we only need the ‘photo’ and ‘name’ to display the comments:
public function scopes()
{
return array(
'api' => array(
'select' => 'photo, name', // only showing these for the comments API call
),
);
}
Posts model has the following relations, a User who created it and many Comments added to it:
public function relations()
{
return array(
'comments' => array(self::HAS_MANY, 'Comments', 'post_id'),
'user' => array(self::BELONGS_TO, 'User', 'user_id'),
);
}
Comments model is set up with the relations connected to both post and the user that created it:
public function relations()
{
return array(
'posts' => array(self::BELONGS_TO, 'Posts', 'post_id'),
'user' => array(self::BELONGS_TO, 'Users', 'user_id'),
);
}
public function defaultScope()
{
return array(
'with' => array('user:api'), // pull the "api" scope of Users model by default. "user" is the name of the relation from this model, "api" is the scope from the User model.
);
}
The following ‘api’ scope for Comments will be merged with the default scope when called.
public function scopes()
{
return array(
'api' => array(
'select' => 'id, comment, date', // only need minimal information for the API from the Comments table/model
),
);
}
Then to get all posts with associated comments and user names and photos to come with the comments we just call this one line:
$data = Posts::model()->with('comments:api')->findAll();