如何将变量从控制器传递给模型 - Yii

时间:2014-07-10 14:01:55

标签: php yii

我目前正在尝试将变量从控制器传递给我的模型。从上一个视图中,我在一个按钮中传递了$ id。

<a class="btn btn-info" type="button" href="index.php?r=recipient/index&id=<?php echo $data->id; ?>">Manage</a>  

从那里,我在我的控制器中访问了$ id并使用它。但是,现在我在模型中创建一个需要使用$ id的函数。我无法将其作为参数传递,因为它是函数beforeSave(在我保存新条目之前更新了我的数据库) 这在模型Recipient.php

中看起来像这样
// before you save the function here are the things you should do
public function beforeSave()
{
    if($this->isNewRecord)
    {

        // updates the list_id of the individual with the selected ListId

        $this->list_id = Recipient::model()->getListId;


    }
    return parent::beforeSave();
} 

最后,我试图在同一个模型中创建函数getListId。

public function getListId()
{
    // my code here 
}

是否有一种简单的方法可以将变量从控制器传递给要使用的模型?或者,有没有办法让模型中的函数访问传递给控制器​​的变量?

1 个答案:

答案 0 :(得分:1)

向模型添加属性并在控制器中设置该属性。

class Model
{
    public $var;
    ... more code ...
}

actionIndex($idList)
{
    $model = Model::model()->find(...);
    $model->var = $idList;
    ... more code ...
}