在产品型号中我有:
public function getImage()
{
return $this->hasMany(Image::className(), ['product_id' => 'id']);
}
public function getMainImage()
{
$image = Image::findOne(['product_id' => $this->id, 'is_main' => 1]);
return $image->path;
}
在视图文件中,我有带_item文件的ListView:
<img src="<?=$model->getMainImage()?>"></img>
控制器:
$dataProvider = new ActiveDataProvider([
'query' => Product::find()->with(['image']),
]);
错误是: 试图获得非对象的属性“路径”。
答案 0 :(得分:0)
如果找不到图像,您提交的代码可能会导致此错误。 你应该包括一个空检查。
public function getMainImage()
{
$image = Image::findOne(['product_id' => $this->id, 'is_main' => 1]);
return $image ? $image->path : false;
}
您可能还希望通过hasOne查看使用AR关系实现此功能,这将更简洁。这里记录在案:
https://www.yiiframework.com/doc/api/2.0/yii-db-baseactiverecord#hasOne()-detail
答案 1 :(得分:0)
你有没有写完整的代码:
return is_null($image) ? false : $image->path;
如果不能正常工作,请检查您的情况!