Search code examples
phpyii2database-relations

Yii2. "With" in ManyToMany


I have 3 models: Image, Company and File. 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?


Solution

  • You'll have to fetch the images first and then provide an extra getter function to return the files:

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