简体   繁体   English

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

[英]How to pass variable from controller to model - Yii

I am currently trying to pass a variable from the controller to my model. 我目前正在尝试将变量从控制器传递给我的模型。 From a previous view I was passed $id in a button. 在以前的视图中,我通过一个按钮传递了$ id。

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

From there, I have accessed $id inside my controller and used it. 从那里,我已经访问了控制器内部的$ id并使用了它。 However, now I am creating a function in the model that needs to use that $id. 但是,现在我正在模型中创建一个需要使用该$ id的函数。 I can't pass it in as a argument because it is the function beforeSave (which updates my database before I've saved a new entry) This looks like this in the model Recipient.php 我不能将其作为参数传递,因为它是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();
} 

Finally, I am trying to create the function getListId in the same model. 最后,我试图在同一模型中创建函数getListId。

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

Is there a simple way to pass a variable from the controller to the model to use? 有没有简单的方法可以将变量从控制器传递到模型以使用? Or, is there a way for a function in the model to access a variable passed to the controller? 或者,模型中的函数是否有办法访问传递给控制器​​的变量?

Add a property to your model and set that property in your controller. 向模型添加属性,然后在控制器中设置该属性。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM