Heilá,
From http://www.yiiframework.com/doc/guide/1.1/en/database.arr#dynamic-relational-query-options
Starting from version 1.0.5, dynamic query options can also be used when using the lazy loading approach to perform relational query. To do so, we should call a method whose name is the same as the relation name and pass the dynamic query options as the method parameter. For example, the following code returns a user’s posts whose status is 1:
$user=User::model()->findByPk(1);
$posts=$user->posts(array('condition'=>'status=1'));
In my Post model I have already defined the condition ‘status=1’
public function scopes() {
return array(
'active'=>array(
'condition'=>'status=1',
),
)
}
So, How can I use (if it’s possible) my scope ‘active’ instead of array(‘condition’=>‘status=1’)
$posts=$user->posts(/* named scope here? */);
mikl
(Mike)
November 11, 2010, 1:56pm
2
Try
User::model()->with('posts:active')->findByPk(1);
Note that you cannot use parameterized scopes, only those defined in the scopes() method of your related model. See here for details:
http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-named-scopes
ricoSaw
(Ricosaw)
November 11, 2010, 1:59pm
3
You have try this?
$posts=$user->with('posts:active')->findAll();
or this
$posts=$user->posts->active()->findAll();
Mike this work too, but is not eager loading approach?
I’d like to use the lazy loading approach as in the docs, but instead of
$posts=$user->posts(array('condition'=>'status=1'));
something like
$posts=$user->posts('active:visible:approved'));
to avoid repeating conditions that I had already defined in scopes()…
I had a look inside CActiveRecord and seems that it doesn’t support this kind of call (with non-parameterized named scopes)…would be soooo good to have!
mikl
(Mike)
November 11, 2010, 4:41pm
5
Ah, right, missed that you where talking about lazy loading. From looking at the source of CActiveRecord::__call() i’d also say it’s not possible but could maybe be implemented as a feature. getRelated() could therefore accept $params to also be a string and interprete this as name of a named scope.
With some luck such a feature request might get accepted.
Ah, right, missed that you where talking about lazy loading. From looking at the source of CActiveRecord::__call() i’d also say it’s not possible but could maybe be implemented as a feature. getRelated() could therefore accept $params to also be a string and interprete this as name of a named scope.
With some luck such a feature request might get accepted.
all right! hope to get lucky…
http://code.google.com/p/yii/issues/detail?id=1755