gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 23:06:18 24 4
gpt4 key购买 nike

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

模型 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');

关于php - 在 yii 中创建具有关系的下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18579823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com