Ar And Joins

As I can see, AR joins was dropped. I suppose the only way to filter results by related model’s fields is to use inner/outerJoin().

E. g.


Comment::find()->active()->innerJoin('tbl_user', 'tbl_comment.user_id=tbl_user.id')

Seems not good for two reasons:

  1. Need to hardcode table names (tbl_user, tbl_comments in my case)

  2. All the ‘scopes’ (active() in my case) should be disambiguated, otherwise we’ll get an error like “Column ‘is_disabled’ in where clause is ambiguous”, which is painful for ‘global’ scopes (defined in model’s parent). For example, I’ve extended base ActiveRecord and add some basic ‘scopes’ there (like active() or last()).

Is there any way to avoid these issues?

Good question.

Hardcoding table names shouldn’t be a big problem because you would have to use it anyway when AR isn’t the way to go.

The column disambiguation is a trouble indeed. In Yii 1.1, this is handled by the framework, which unfortunately has side effect too. Perhaps for Yii 2, whenever you write a scope, you should always prefix column names with table names.

Less magic is better, I just wanted to know if I’ve missed something.

Is this good?




namespace app\components;

class ActiveRecord extends \yii\db\ActiveRecord

{

    public static function active($query)

    {

        $query->andWhere(static::tableName() . '.is_disabled = 0');

    }

...

}