Search code examples
yii2relationships

Several identical relations to one model in Yii2


I have a model File to store uploaded files and information about these files. Also there is a model with Company relations logo hasOne(File::className()) and photos hasMany(File::className()). Relations are written and works fine. Now I need to make an edit form for model Company in which I could edit files associated in logo and photos. Please tell me how I can do it.


Solution

  • Your relations can reflect the different use-cases, so in your Company model you can have

    public function getLogo(){
        //You'll need to add in the other attributes that define how Yii is to retrieve the logo from your images
        return $this->hasOne(File::className(), ['companyId' => 'id', 'isLogo' => true]);
    }
    
    public function getPhotos(){
        //You'll need to add in the other attributes that define how Yii is to retrieve the photos from your images
        return $this->hasMany(File::className(), ['companyId' => 'id', 'isLogo' => false]);
    }
    

    You can then just use them like normal attributes;

    $company = new Company;
    $logo = $company->logo;
    $photos = $company->photos;
    

    You will then need to set up your controller to handle changes in these values to deal with uploads or new images, but that will depend on how you are handling the uploads.