I have two models, with relation via junction table. So, i am trying to get from db some models, that have not this relation.
I can do this by this way.
But how to do this by query ? Use with or joinWith methods, and check IS NULL
at junction table columns ?
Asked
Active
Viewed 2,476 times
1

Community
- 1
- 1

Max Maximov
- 123
- 2
- 12
-
Yes, exactly like that. – Bizley Dec 08 '16 at 07:12
1 Answers
2
Create junction's model and add to your AR model method for it:
/**
* @return ActiveQuery
*/
public function getJunctions()
{
return $this->hasMany(Junction::className(), ['someId' => 'id']);
}
Then you can use it with query:
$query = Model::find()
->joinWith([
'junctions' => function (\yii\db\ActiveQuery $query) {
$query->andWhere(['{{junction}}.id' => null]);
}
], false);

SiZE
- 2,217
- 1
- 13
- 24
-
1In my case, i am not create a relation to junction table, but has one, that using it. So, i have a query like yours, data was empty (i think the reason is in relation method). I change andWhere -> where and using default left join. And in this way, query is works. Thanks! – Max Maximov Dec 08 '16 at 07:47
-
-
-
You right about `where`, but in which case i am not need first level conditions. In another case, `andWhere` is rather `where`. – Max Maximov Dec 08 '16 at 08:24