1

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 ?

Community
  • 1
  • 1
Max Maximov
  • 123
  • 2
  • 12

1 Answers1

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
  • 1
    In 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
  • where clear all previous conditions (f.e from behaviors). – SiZE Dec 08 '16 at 08:16
  • As you mentioned must use LEFT JOIN for this. My fault. – SiZE Dec 08 '16 at 08:16
  • 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