【问题标题】:Yii2 pass query result to a action in another controllerYii2 将查询结果传递给另一个控制器中的操作
【发布时间】:2017-03-02 01:03:37
【问题描述】:

我正在尝试在更新任何其他表中的记录时将记录插入到我的审计表中。例如,如果用户更新他的个人资料,我想将旧记录和新更新的记录存储在我的审计表中。为此,在我的用户模型中,我尝试使用 beforeSave() 并将值传递给我的审计控制器

public function beforeSave($insert)
    {
        if((parent::beforeSave($insert))){
                        // Place your custom code here
                        $query = DepCustomer::findOne($this->customer_id);
                        Yii::$app->runAction('audit-trial/createaudit', ['query' => $query]);
                return true;
        }
    } 

现在审核控制器中的操作代码

public function actionCreateaudit($query)
{
    $model = new Audit();

            $model->old = '';
            foreach($query as $name => $value){
                //$temp = $name .': '. $value.',  ';
                //$contentBefore[] = $temp;
                $audit->old = $audit->old.$name .': '. $value. ', ';
            } 
            // I've not yet any other code for now I'm trying to get the old value
            $model->save();
}

我收到 404 not found 错误。我需要对代码进行哪些更改才能使其正常工作?谢谢!

【问题讨论】:

  • 你在“createaudit”这个动作中有什么特殊的逻辑吗,如果你不为什么不在 beforesave 方法中保存查询。如果您有特殊逻辑,最好将其移至模型“AuditTrial”,然后您可以从代码中的任何位置调用它
  • 是的!这是真的。我可以在 beforesave 方法或客户控制器的更新操作中保存新旧更新数据,我已经实现了这一点。现在我也在尝试保存其他模型的审计记录。所以我正在尝试编写代码以在 beforesave 方法中传递旧值,以便我也可以将代码放入其他模型中。

标签: yii2 audit


【解决方案1】:

而不是 runAction() 。如果您想对另一个模型执行操作,最好在该模型(在您的情况下为 Audit 模型)中创建一个静态函数来保存数据

public function beforeSave($insert)
    {
        if((parent::beforeSave($insert))){
                        // Place your custom code here
                        $query = DepCustomer::findOne($this->customer_id);
                       Audit::saveOldDetails($query);
                return true;
        }
    } 

并在Audit Model中写入saveOldDetails函数

public static saveOldDetails($query){
 // your business logic here
}

参考这个链接 http://www.yiiframework.com/doc-2.0/yii-base-controller.html#runAction()-detail

【讨论】:

  • 嗨!使用这种方法,同一条记录被多次插入审计表。喜欢3次。我一直在试图找出造成这种情况的原因,但找不到原因。知道是什么原因造成的吗?
  • beforeSave 将为每个保存方法执行。
  • 好的。不知道那个。我的更新操作中有多个 save() 。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-13
  • 1970-01-01
  • 2012-07-19
  • 1970-01-01
  • 1970-01-01
  • 2021-02-04
  • 2014-03-05
相关资源
最近更新 更多