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

Dmi*_*kov 4 php entity-relationship html-select yii

我是 Yii 框架的新手,现在我尝试从相关表创建下拉列表。我有表“新闻”[...很多字段,类别] 和“新闻类别”[id,category_name]。在用于在新闻中创建新记录的表单中,当用户可以选择 category_name 时,我想在类别字段中创建一个下拉列表,但类别的 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'),
    );
}
Run Code Online (Sandbox Code Playgroud)

模型新闻Categories.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'),
    );
}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 5

指定关系时,不需要指定主键(id),因为 yii 可以从模型中推导出主键。您只需要指定另一端,因此您的 NewsCategory 关系应如下所示:

'news'=>array(self::HAS_MANY, 'News', 'category'),
Run Code Online (Sandbox Code Playgroud)

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

CHtml::listData(NewsCategories::model()->findAll(), 'id', 'category_name');
Run Code Online (Sandbox Code Playgroud)