Apply criteria on lazy loading

Hey everyone,

I’m working on a project which makes heavy use of active record relations. There are countless situations where I need to get e.g. the user’s relation to content records. So most of the time I build a query with scopes adding params like Yii::app()->user->id eagerly loading everything I need at once. But there are times where I would love to fall back to lazy loading, for example if it’s uncommon that a related record will be needed.

So here is the thing: I want to always apply some criteria when a relation is lazy loaded. So if I call $model->membership but the relation “membership” wasn’t already loaded it would do a getRelated(“membership”, true, array(“on”=>“userId=”.Yii::app()->user->id)) call instead. There are several ways to do this, override the __get() method or rename the relation to “_membership” and build a wrapper getMembership().

My question is, what is the most effective one, especially considering I have 40+ relations I want to work that way.

Thank you for your feedback!!!


Just ran across a similar need in my project. Apparently you can do lazy-load relationships with scopes, something I hadn’t found clear at all in the Yii guide.

Here’s the initial discussion / bug report:

Here’s a comment I found quite helpful in getting it working:

and here’s a rough guide to the syntax:

$user = User::model()->findByPk((int)1);

$allPosts = $user->posts;

// filtered posts, using an unapproved scope in the Posts model

$unapprovedPosts = $user->posts('posts:unapproved');

Theoretically, it should work with parameterized scopes as well. Does that help?