Search code examples
activerecordrelational-databaseyii2junction-table

yii2: get records by relations id


I have Images model with relation:

public function getAlbums()
{
    return $this->hasMany(ImagesTerms::className(), ['id' => 'term_id'])
                ->viaTable(ImagesTermsRelations::tableName(), ['object_id' => 'id'])
                ->andWhere(['type'=>'album']);
}

On image view page I want to show random images with the same albums. Can anyone help?

I tried with the following query, but it didn't gave me what I want:

$related = Images::find()->with([
        'albums' => function($query) {
            $query->andWhere(['in', 'id', [2]]);
        }
])->where(['status'=>'1'])->orderBy('rand()')->limit(9)->all();

This query excludes other albums, but not images. Images with other albums are shown, but without album tag.


Solution

  • I solved the problem:

    $related = Images::find()->joinWith([
        'albums' => function($query) {
            $query->andWhere(['in', 'images_terms.id', [1,2,3]);
        }
    ])->where(['images.status'=>'1'])->orderBy('rand()')->limit(9)->all();