在yii中创建具有关系的下拉列表


Creating dropdownlist with relations in yii

我是Yii框架的新手,现在我尝试从相关的表中创建dropdownlist。我有表格"新闻"[…很多字段,类别]和"新闻类别"[id,类别名称]。在新闻中创建新记录的表单中,当用户可以选择类别名称时,我想在类别字段中创建一个下拉列表,但类别的id必须是新记录中的记录器。

请帮帮我。对不起我的英语。我希望我所解释的可以理解。

以下是我如何创建关系

型号新闻.php

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, 'NewsCategories', 'category'),
    );
}

模型新闻分类.php

    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(
    'news'=>array(self::HAS_MANY, 'News', 'id'),
    );
}

以及我如何尝试创建下拉列表:

<?php echo $form->dropDownList($model,'category',CHtml::listdata(News::model()->with('category')->findAll(),'id','category_name'),array('empty'=>'(Select a category')));?>

在指定关系时,不需要指定主键(id),因为yii可以从模型中扣除主键。你只需要指定另一端,所以你的NewsCategory关系应该是这样的:

'news'=>array(self::HAS_MANY, 'News', 'category'),

要获得适合下拉列表的数据,请使用

CHtml::listData(NewsCategories::model()->findAll(), 'id', 'category_name');