我有一個關係函數,當數據庫中有一個image_name時,它完美地工作。Yii2關係功能
我可以使用$model->fromProfile->mainImage->image_name
得到圖像文件名,它可以工作。
但是,如果查詢返回whiteout image_name(如果用戶沒有上傳任何適合查詢的圖像),我會收到一個錯誤,說「試圖獲取非對象的屬性」。
但是爲什麼?我在應該處理這個函數的函數中有一個規則,函數應該檢查image_name是否存在,如果沒有,image_name應該是'no_image.jpg';
這是應該處理這個案件的功能:
public function getMainImage(){
$mainImage = $this->hasOne(Image::className(), ['profile_id' = > 'profile_id'])
->andOnCondition(['main' = > '1']);
if (!isset($mainImage->image_name)) {
$mainImage = new Image();
$mainImage->image_name = 'no_image.jpg';
}
return $mainImage;
}
這是剖面模型:
public static function tableName(){
return 'tbl_user_profile';
}
public function rules(){
return[
[['user_id'], 'required'],
[['user_id'], 'integer'],
[['place'], 'in', 'range' = >array_keys(self::PLACE)],
[['meeting'], 'in', 'range' = >array_keys(self::MEETING)],
[['expiriance'], 'in', 'range' = >array_keys(self::EXPIRIANCE)],
[['lookingfor'], 'in', 'range' = >array_keys(self::LOOKINGFOR)],
[['about'], 'string'],
[['user_id'], 'exist', 'skipOnError' = > true, 'targetClass' = > User::className(), 'targetAttribute' = >['user_id' = > 'user_id']],
];
}
public function attributeLabels(){
return[
'profile_id' = > 'Profile ID',
'user_id' = > 'User ID',
'about' = > 'about',
'place' = > 'place',
'meeting' = > 'meeting',
'expiriance' = > 'expiriance',
'lookingfor' = > 'Looking for',
];
}
public function getMainImage(){
$mainImage = $this->hasOne(Image::className(), ['profile_id' = > 'profile_id'])
->andOnCondition(['main' = > '1']);
if (!isset($mainImage->image_name)) {
$mainImage = new Image();
$mainImage->image_name = 'no_image.jpg';
}
return $mainImage;
}
這是圖像模式:
public static function tableName(){
return 'tbl_images';
}
public function rules() {
return[
[['profile_id', 'image_name'], 'required'],
[['profile_id', 'is_private', 'main'], 'integer'],
['image_name', 'image', 'minWidth' = > 250, 'minHeight' = > 250, 'extensions' = > 'jpg, gif, png, jpeg', 'maxSize' = > 1024 * 1024 * 2],
[['image_name'], 'string', 'max' = > 255],
[['profile_id'], 'exist', 'skipOnError' = > true, 'targetClass' = > Profile::className(), 'targetAttribute' = >['profile_id' = > 'profile_id']],
];
}
public function attributeLabels(){
return[
'image_id' = > 'Image ID',
'profile_id' = > 'Profile ID',
'image_name' = > 'Image Name',
'is_private' = > 'Private Image',
'main' = > 'Main Image',
];
}
public function getUser(){
return $this->hasOne(User::className(), ['user_id' = > 'user_id']);
}
public function getViewers(){
return $this->hasOne(View::className(), ['viewed_profile_id' = > 'profile_id']);
}
public function getProfile(){
return $this->hasOne(Profile::className(), ['profile_id' = > 'profile_id']);
}
AREV確定爲列名? ...更新你的問題,並添加你圖像模型和模型,你有功能getMainImage – scaisEdge
請添加個人資料模型.. – scaisEdge
我添加了個人資料模型 –