微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 使用yii中的关系创建下拉列表

我是Yii框架中的新手,现在我尝试从相关表创建下拉列表.
我有表“新闻”[…很多字段,类别]和“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'),
    );
}

Model 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')));?>

解决方法:

指定关系时,您不需要指定主键(id),因为yii可以从模型中扣除主键.您只需指定另一端,因此您的Newscategory关系应如​​下所示:

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐