如何判断我是否处于编辑或创建之前的保存状态?蛋糕PHP

发布于 2024-08-11 23:55:46 字数 139 浏览 3 评论 0原文

我有一个模型,需要在保存之前进行一些处理(或在某些情况下进行编辑),但通常在简单编辑时不需要。事实上,如果我对大多数编辑进行处理,结果字段将是错误的。现在,我正在模型的 beforeSave 回调中工作。如何判断我是来自编辑还是添加?

弗兰克·卢克

I have a model where I need to do some processing before saving (or in certain cases with an edit) but not usually when simply editing. In fact, if I do the processing on most edits, the resulting field will be wrong. Right now, I am working in the beforeSave callback of the model. How can I tell if I came from the edit or add?

Frank Luke

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苏大泽ㄣ 2024-08-18 23:55:46
function beforeSave() {
  if (!$this->id && !isset($this->data[$this->alias][$this->primaryKey])) {
    // insert
  } else {
    // edit
  }
  return true;
}
function beforeSave() {
  if (!$this->id && !isset($this->data[$this->alias][$this->primaryKey])) {
    // insert
  } else {
    // edit
  }
  return true;
}
╭ゆ眷念 2024-08-18 23:55:46

这基本上与 neilcrookes 的答案相同,除了我使用 empty() 作为测试,而不是 !isset( )

如果数组键存在,但为空,则 !isset 将返回 false,而empty 将返回 true。

我喜欢使用相同的视图文件进行添加和编辑,以保持代码干燥,这意味着在添加记录时,“id”键仍将被设置,但不会保留任何内容。 Cake 可以很好地处理这个问题,但 neilcrookes 版本的代码不会将其识别为添加,因为 PrimaryKey 键是在数据数组中设置的(即使它不包含任何内容)。因此,将 !isset 更改为空就可以解决这种情况。

function beforeSave() {
  if (!$this->id && empty($this->data[$this->alias][$this->primaryKey])) {
    // insert
  } else {
    // edit
  }
  return true;
}

This is basically the same as neilcrookes' answer, except I'm using empty() as the test, as opposed to !isset().

If an array key exists, but is empty, then !isset will return false, whereas empty will return true.

I like to use the same view file for add and edit, to keep my code DRY, meaning that when adding a record, the 'id' key will still be set, but will hold nothing. Cake handles this fine, except neilcrookes version of the code won't recognise it as an add, since the primaryKey key is set in the data array (even though it holds nothing). So, changing !isset to empty just accounts for that case.

function beforeSave() {
  if (!$this->id && empty($this->data[$this->alias][$this->primaryKey])) {
    // insert
  } else {
    // edit
  }
  return true;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文