Yii Framework Forum: Apply criteria on lazy loading - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Apply criteria on lazy loading Best practice / Possible extension Rate Topic: -----

#1 User is offline   dmx 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 24
  • Joined: 08-November 10

Posted 20 June 2012 - 11:00 AM

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!!!

Dmx
0

#2 User is offline   fr0d0z 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 86
  • Joined: 25-February 11
  • Location:CO, USA

Posted 31 August 2012 - 01:50 PM

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:
http://www.yiiframew...-query-troubles

Here's a comment I found quite helpful in getting it working:
http://www.yiiframew...tabase.arr#c565

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?
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users