我是 PHP 和 yii 框架的新手,所以我需要下拉菜单方面的帮助。在我的数据库中,我有 2 个表 - 类别 - id、名称和新闻 - id、标题、内容、category_id。我怎样才能在这两个控制器之间建立关系?当我发布新闻时,我必须从下拉菜单中选择类别。我很抱歉这个愚蠢的问题,但我现在不能这样做。
问问题
1129 次
3 回答
1
只需将其放在您的新闻模型中:
/**
* @return array relational rules.
*/
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, 'Category', 'category_id'),
);
}
这在您的类别模型中:
/**
* @return array relational rules.
*/
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(
'newsItems' => array(self::HAS_MANY, 'News', 'category_id'),
);
}
每当您拥有类别的实例时,您都可以像这样引用多个新闻项目:
$category = Category::model()->findByPk(1);
$category->newsItems; //an array of News objects
您可以像这样参考该类别:
$news = News::model()->findByPk(1);
$category = $news->category; //a Category object
于 2012-08-16T18:50:28.390 回答
0
我认为您在创建新闻项目时询问如何显示所有类别以供选择。在您创建新闻对象的表单中,您需要以下内容:
$cats = Category::model()->findAll();
$cats = CHtml::listData($cats, 'id', 'name');
$form->dropDownList($model, 'category', $cats);
对于它们之间的关系以及之后访问它,请参阅 Benjamin Bytheway 的回答
于 2012-08-17T08:50:27.520 回答
0
您可以像这样在一行中完成 paystey 所写的所有内容:
<?php echo $form->dropDownList($model,'Category', CHtml::listData($CategoryModel::model()->findAll(array('order'=>'Text ASC')), 'CategoryID', 'Text'), array('empty'=> ' -- Select A Category -- '));?>
列表数据的最后一个参数就是页面加载时应该显示的内容。
于 2012-08-17T14:09:06.623 回答