I am working with Yii framework 2.0, I have one database table that looks like the following.
id active key
1 0 xx
2 1 xx
3 0 zzz
4 0 wwww
5 1 wwww
6 1 qqqqq
I would like to get the record where 'active' is 1 and 'key' is the same as 'key' of the record where 'active' is 0. The result that I want is
id active key
2 1 xx
5 1 wwww
It might not be easy to understand the question, so I put following code sample to support the question. This codes gives me the result I want.
$allModel = Model::find()->where(['active' => 0])->all();
$arrModelActive1 = [];
foreach($allModel as $model) {
$modelActive1 = Model::find()->where['active' => 1, 'key' => $model->key]->all();
$arrModelActive1[] = $modelActive1;
}
return $arrModelActive1;
I could approach this problem with the above code sample, but the problem is that I execute the query inside of the foreach loop which might decrease the performance. So I am looking for a join or an eager loading solution which Yii 2.0 might provide which could operate with the same table or so-called self-join operation.