yii2:通过关系 id 获取记录

yii2: get records by relations id

我有关联的图像模型:

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

在图像查看页面上,我想显示具有相同相册的随机图像。有人可以帮忙吗?

我尝试了以下查询,但没有得到我想要的结果:

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

此查询不包括其他相册,但不包括图像。显示了其他相册的图像,但没有相册标签。

我解决了问题:

$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();