yii中的模型关系

时间:2015-08-20 11:55:40

标签: php yii

我在我的模型中写了一个像这样的关系

public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
        'category' => array(self::BELONGS_TO, 'Category', 'categoryid'),
        'company' => array(self::BELONGS_TO, 'CommercialUser', 'createdby'),
        'subcategory' => array(self::BELONGS_TO, 'SubCategory', 'subcategory'),
    );
}

我创建了一个带子类别字段的视图页面,并通过数组

调用它

我的观点

    <?php $this->widget('zii.widgets.CDetailView', array(
    'data'=>$model,
    'attributes'=>array(
        //'id', 
        array( 
            'name' => 'type',
            'type' => 'raw',
            value'=>$model->type

            ),
        'title',
        'description',
        array( 
            'name' => 'Category',
            'type' => 'raw',
            'value'=>$model->category->categoryname 
            ),
         'subcategory',
         array( 
            'name' => 'subcategory',
            'type' => 'raw',
            'value'=>$model->subcategory->subcategory_name 
            ),
        'location',
        'startdate',
        'enddate', 



            array( 
            'name' => 'image',
            'type' => 'raw',
            'value'=>GFunctions::GetoffereveImage($model->id) 
            ),
    ),
)); ?>  

我的数据库中有一个名为sub_category的表 我需要的是与该表建立关系以获得subcategory_name ...
当我尝试它时显​​示出像

这样的错误

尝试获取非对象的属性

请有人帮我解决这个问题。
谢谢

1 个答案:

答案 0 :(得分:0)

首先检查类别和子类别字段是否为空。

'value'=> ($model->subcategory) ? $model->subcategory->subcategory_name : null;
'value'=> ($model->category) ? $model->category->category_name : null;
相关问题