Yii 在形式中使用关系属性


Yii using relational attributes in form

在我的Yii应用程序中,我有两个表,分别是"producer_offer"和"book_vegetable"。我在表中有一个名为"book_vegetable_id"producer_offer列,它是"producer_offer"表的主键列"id"的外键。

现在我想引用"producer_offer"表中"book_vegetable"表的名为"booked_quantity"的列。我想在视图表单中引用此列。我在"producer_offer"表中的关系函数代码。

public function relations()
    {
 'producerOfferBookVegetable'=>array(self::BELONGS_TO,'BookVegetable','book_vegetable_id')
        );
    }

在表单中,我想输入"book_vegetable"表的"booked_quantity"值。我应该怎么做?

我认为这就是您要做的:

控制器.php

public function actionCreate()
{
    $modelBV=new BookVegetable;
    $modelPO=new ProducerOffer;
    if(isset($_POST['BookVegetable']) AND isset($_POST['ProducerOffer'])) {
        $modelBV->attributes=$_POST['BookVegetable'];
        $modelPO->attributes=$_POST['ProducerOffer'];
        if($modelBV->validate()  AND  $modelPO->validate()) {
            $modelBV->save()
            $modelPO->book_vegetable_id = $modelBV->id;
            $modelPO->save();
        }
    }
    $this->render('create',array(
        'modelBV'=>$modelBV,
        'modelPO'=>$modelPO,
    ));
}

或者您可以使用如下扩展:https://github.com/yiiext/with-related-behavior