Relational AR with named scopes?

Let’s say I have two models, Post and Author.

Post has a named scope, implemented by a method named published().

Author has a named scope, implemented by a method named active().

I can produce a list of published Posts using Post::model()->published()->findAll().

I can produce a list of active authors using Author::model()->active()->findAll().

I can produce a list of Posts with their Authors using Post::model()->published()->with(‘authors’)->findAll().

But now suppose I want to produce a list of published() Posts by active() authors.

It seems that, once you call CActiveRecord::with(), you break the chain and leave your static CActiveRecord instance behind - because with() returns a CActiveFinder instance instead, and you’re now in relational land, thus leaving behind your named scope functions, which are only available on your CActiveRecord instance.

Is there any way to combine named scopes from two different models in a single query?

Yes! If I don’t rememeber wrong you can do semething like:

Post::model()->published()->with(‘authors:active’)->findAll()

Try it!!!

That works for simple scopes defined using scopes(), but for named scopes (using functions) this results in an exception.

I don’t think this feature is documented?

And the limitation of being able to only use non-parametrized scopes could be lifted as well - for example, to apply a parametrized scope named ofAge to join with Users at least 18 years old, I would propose a syntax like with(array('user', 'scope'=>array('ofAge', 18))) (e.g. equivalent to User::model()->ofAge(18) in a non-relational query.

I added a comment to the documentation:

http://www.yiiframework.com/doc/api/CActiveRecord

What should we do with named scopes? Is there any workaround?