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

时间:2015-03-27 14:32:10

标签: yii2 relationships

我有一个模型文件来存储上传的文件和有关这些文件的信息。还有一个模型与公司关系标志hasOne(File :: className())和照片hasMany(File :: className())。关系写得很好。现在我需要为model Company制作一个编辑表单,我可以在其中编辑徽标和照片中的文件。请告诉我如何做到这一点。

1 个答案:

答案 0 :(得分:0)

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

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;

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