I have two related models with default scopes defining a condition with a userId column.
This one:
class BankTransaction extends CActiveRecord
{
...
public function relations()
{
return array(
'category' => array(self::BELONGS_TO, 'Category', 'categoryId'),
);
}
public function defaultScope()
{
return array(
'alias'=>'bt',
'condition'=>'bt.userId = '.Yii::app()->user->id,
);
}
}
And this one:
class Category extends CActiveRecord
{
...
public function defaultScope()
{
return array(
'alias'=>'c',
'condition'=>'c.userId = '.Yii::app()->user->id,
);
}
}
When retrieving BankTransaction data using a CDBDataProvider with the CDBCriteria containing the ‘with’ clause with the relation ‘category’:
$dataProvider=new CActiveDataProvider('BankTransaction', array(
'criteria'=>array(
'condition'=>'te.accountId = '.$accountId,
'with'=>array('category'),
),
));
The framework is generating the following SQL command:
SELECT "bt"."id" AS "t0_c0", ...
FROM "bank_transaction" "bt"
LEFT OUTER JOIN "category" "c"
ON ("bt"."categoryId"="c"."id")
WHERE ((bt.userId = 1) // *
AND ((bt.userId = 1) // **
AND (bt.accountId = 5)))
AND (c.userId = 1) // ***
As we can see, it is adding the default condition twice(*, **) to the data provider model, maybe because the addional condition, but it is unnecessary.
Is this an issue worth a ticket?
But the thing that invalidates the LEFT OUTER JOIN clause is the last WHERE condition (***), added probably because of the default scope of the Category model.
The result set only shows BankTransactions that have Categories defined.
The correct SQL command would add the Category model default scope condition in the LEFT OUTER JOIN conditions (ON).
Is this a bug or I am doing something wrong?
Should I open a ticket?
Thank you!