Default scope invalidates LEFT OUTER JOIN

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!

Any thoughts guys? :huh:

Am I doing something wrong? I had another issue with the default scope.

Andre, I’m having a similar or identical issue. Please let me know if you found a solution. I’ll provide a fix/work-around if resolved.

nc

Andre, upgrade to 1.1.3, the issue appears corrected (ie, the default scope conditions are part of the join and not the main query’s where condition.

There is also now the AR resetScope() method that will be useful in creating defaultScope exceptions.

Best,

nc