yii2:通过关系 id 获取记录

Posted

技术标签:

【中文标题】yii2:通过关系 id 获取记录【英文标题】:yii2: get records by relations id 【发布时间】:2015-07-26 07:56:25 【问题描述】:

我有具有关系的图像模型:

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

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

【问题讨论】:

【参考方案1】:

我解决了这个问题:

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

【讨论】:

以上是关于yii2:通过关系 id 获取记录的主要内容,如果未能解决你的问题,请参考以下文章