我是Yii框架中的新手,现在我尝试从相关表创建下拉列表。我有表格“新闻”...a很多字段,类别和"NewsCategories"id,category_name。在新闻中创建新记录的形式中,当用户可以选择category_name时,我希望在类别字段中创建一个下拉列表,但是类别的id必须是新记录中的记录器。
请帮帮我。对不起我的英语。我希望我的解释可以理解。
以下是我是如何建立关系的
News.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'),
);
}
NewsCategories.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')));?>
发布于 2013-09-02 11:59:24
在指定关系时,不需要指定主键(id),因为yii可以从模型中扣除主键。您只需要指定另一端,因此NewsCategory关系应该如下所示:
'news'=>array(self::HAS_MANY, 'News', 'category'),
若要获取适合下拉列表的数据,请使用
CHtml::listData(NewsCategories::model()->findAll(), 'id', 'category_name');
https://stackoverflow.com/questions/18579823
复制