Yii2中一个模型的几个相同关系

Several identical relations to one model in Yii2

我有一个模型文件来存储上传的文件和有关这些文件的信息。还有一个带有公司关系徽标的模型 hasOne(File::className()) 和照片 hasMany(File::className())。关系是书面的并且工作正常。现在我需要为模型公司制作一个编辑表单,我可以在其中编辑与徽标和照片相关的文件。请告诉我该怎么做。

您的关系可以反映不同的用例,因此在您的公司模型中您可以拥有

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]);
}

然后您可以像使用普通属性一样使用它们;

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

然后您需要设置您的控制器来处理这些值的变化以处理上传或新图像,但这将取决于您处理上传的方式。