在CakePHP中,如何确定在编辑操作中是否更改了字段? [英] In CakePHP, how can you determine if a field was changed in an edit action?

查看:113
本文介绍了在CakePHP中,如何确定在编辑操作中是否更改了字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用中的 cacheCounter 中增加了相关字段的计数器。

I'm using the cacheCounter in CakePHP, which increments a counter for related fields.

例子,我有一个Person表一个Source表。 Person.source_id映射到源表中的一行。每个人都有一个来源,每个来源没有或许多人行。

Example, I have a Person table a Source table. Person.source_id maps to a row in the Source table. Each person has one Source, and each Source has none or many Person rows.

cacheCounter 更改某人的来源的值。它增加 Source.Person_Count 。很酷。

cacheCounter is working great when I change the value of a source on a person. It increments Source.Person_Count. Cool.

但是当它增加时,它会将其添加到某个人的目标源,但不会将其从旧值中删除。我在 afterSave 中尝试了 updateCacheControl(),但没有做任何事。

But when it increments, it adds it to the destination source for a person, but doesn't remove it from the old value. I tried updateCacheControl() in afterSave, but that didn't do anything.

然后我在我的模型中写了一些代码,用于 afterSave ,它会减去源代码source_id,但是它总是这样,即使我不是更改 source_id 。 (所以计数变为负数)。

So then I wrote some code in my model for afterSave that would subtract the source source_id, but it always did this even when I wasn't even changing the source_id. (So the count went negative).

我的问题:有没有办法告诉如果一个字段在 code>?

My question: Is there a way to tell if a field was changed in the model in CakePHP?

推荐答案

要监视字段中的更改,可以在模型中使用此逻辑,必需:

To monitor changes in a field, you can use this logic in your model with no changes elsewhere required:

function beforeSave() {
    $this->recursive = -1;
    $this->old = $this->find(array($this->primaryKey => $this->id));
    if ($this->old){
        $changed_fields = array();
        foreach ($this->data[$this->alias] as $key =>$value) {
            if ($this->old[$this->alias][$key] != $value) {
                $changed_fields[] = $key;
            }
        }
    }
    // $changed_fields is an array of fields that changed
    return true;
}

这篇关于在CakePHP中,如何确定在编辑操作中是否更改了字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆