Yii Many_Many Relationship and Form

时间:2010-12-25 19:27:33

标签: yii

// Post model
return array(
    'categories' => array(self::MANY_MANY, 'Category', 'categories_posts(post_id, category_id)')
);

我已经设置了表格

posts
id, title, content

categories
id, name

categories_posts
post_id, category_i

我遇到的问题是我在创建此表单时遇到错误:

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'post-form',
    'enableAjaxValidation'=>false,
)); ?>

    <p class="note">Fields with <span class="required">*</span> are required.</p>

    <?php echo $form->errorSummary($model); ?>

    <div class="row">
        <?php echo $form->labelEx($model,'title'); ?>
        <?php echo $form->textField($model,'title',array('size'=>60,'maxlength'=>255)); ?>
        <?php echo $form->error($model,'title'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'uri'); ?>
        <?php echo $form->textField($model,'uri',array('size'=>60,'maxlength'=>255)); ?>
        <?php echo $form->error($model,'uri'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'content'); ?>
        <?php echo $form->textArea($model,'content',array('rows'=>6, 'cols'=>50)); ?>
        <?php echo $form->error($model,'content'); ?>
    </div>

    <div class="row">
        <?php // echo $form->labelEx($model,'content'); ?>
        <?php echo CHtml::activeDropDownList($model,'category_id', CHtml::listData(Category::model()->findAll(), 'id', 'name')); ?>
        <?php // echo $form->error($model,'content'); ?>
    </div>

    <div class="row buttons">
        <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
    </div>

<?php $this->endWidget(); ?>

错误是:

Property "Post.category_id" is not defined.

我很困惑。我该怎么做才能纠正这个问题?

3 个答案:

答案 0 :(得分:3)

我使用CAdvancedArBehavior使这更容易。如果像这样的东西最终被卷入Yii核心,我不会感到惊讶:

http://www.yiiframework.com/extension/cadvancedarbehavior/

它允许您在控制器中编写这样的代码:

$model->categories = $_POST['Post']['categories'];

我将它用于比我想要的“关系”小部件/扩展更多的bugggy。您可能需要使用它来正确构造POST变量,我不确定。

答案 1 :(得分:2)

老实说,我认为Yii在他们的AR中有类似Kohana或Cake的东西。我想我必须手动添加它们。

foreach ($_POST['category_id'] as $category_id)
{
    $categoryPost = new CategoryPost;
    $categoryPost->category_id = $category_id;
    $categoryPost->post_id = $model->id;
    $categoryPost->save();
}

答案 2 :(得分:1)

以这种方式使用: 在控制器中 为类别创建对象:$modelCat= new Category;

<?php echo CHtml::activeDropDownList(**$modelCat**,'category_id', CHtml::listData(Category::model()->findAll(), 'id', 'name')); ?>