I want to use the same scope in all cases when I am using the model. There are at least three cases when same model can be used with the same scope. The example below refers to the model User and scope enabled().
- In simple query:
$users = User::model()->enabled()->findAll();
- In relational query with User being the primary table
$users = User::model()->enabled()->with('company')->findAll();
- In relational query with User being secondary table:
$inventory = Inventory::model()->with('user:enabled')->findAll();
If I define ‘enabled’ scope using standard construct:
'enabled' => array('condition'=>'t.enabled=\'Y\'')
I will get "Unknown column t.enabled" in the relational query no 3, because the SQL will look like this:
select * from inventory t inner join user user on user.id = t.userId where t.enabled = 'Y'
The solution would be to define the scope with ‘user’ alias:
'enabled' => array('condition'=>'user.enabled=\'Y\'', 'alias'=>'user')
Indeed, in queries 1 and 3 everything is fine now, but the second query now complains about "unknown column user.enabled’, because the query looks like this:
select * from user t inner join company company on company.id = t.companyId where user.enabled = 'Y'
The reason for this is that CActiveFinder will ALWAYS use ‘t’ as prefix for the primary query model. If I have a scope defined I should be able to use it with no changes in all three situations.
Sorry, but this change had so far introduced more problems that it is trying to fix. The solution could be to introduce an application-wide configuration option to use ‘t’ or table name. For now, I ask everybody to vote if they like the new change or they want their table names back.