简体   繁体   English

Yii2。 ManyToMany中的“ With”

[英]Yii2. “With” in ManyToMany

I have 3 models: Image, Company and File. 我有3个模型:图像,公司和文件。 So if we look through Company model, we have: 因此,如果我们查看公司模型,我们将:

/**
* @return \yii\db\ActiveQuery
*/
public function getImages()
{
    return $this->hasMany('galleries\models\Image', ['id' => 'image_id'])
        ->viaTable('{{%companies_has_images}}', ['company_id' => 'id']);
}

public function extraFields()
{
    return ['images'];
}

now an Image model: 现在是一个图像模型:

    /**
* @return \yii\db\ActiveQuery
*/
public function getFile()
{
    return $this->hasOne('app\models\File', ['id' => 'file_id']);
}

public function extraFields()
{
    return ['file'];
}

So here is the question, how can i get images with correct files in getImages() in the Company model? 所以这是一个问题,如何在Company模型的getImages()中获取带有正确文件的图像?

You'll have to fetch the images first and then provide an extra getter function to return the files: 您必须先获取图像,然后提供一个额外的getter函数以返回文件:

public function getImageFiles() 
{
    $files = [];
    foreach ($this->images as $image)
       $files[] = $image->file;
    return $files;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM