I love using scopes in Yii2, but they seem to break down when you’re filtering on related tables:
an example:
Model A has two scopes which rely on fields which in a related table, table_b:
public function scope1() {
$this->joinWith('table_b');
$this->andWhere(['table_b.property_a' => 1]);
return $this;
}
public function scope2() {
$this->joinWith('table_b');
$this->andWhere(['table_b.property_b' => 0]);
return $this;
}
when I use:
Model_A::find()
->scope1()
->scope2()
It joins the same table twice. I know I can disambiguate with:
$this->joinWith('table_b alias_1');
But it will still join on table_b twice when it runs the query (unnecessarily), and if I add a “where”, or “orderBy” clause to my query, I’ll need to remember to use one of the aliases in the scope (alias_1) rather than the table name.
Is there any way around this? I suspect not, but I thought I’d ask.
-Charlie