【问题标题】:CakePHP 3 - Strange behavior $this->set(); affected after settingCakePHP 3 - 奇怪的行为 $this->set();设置后受影响
【发布时间】:2016-02-02 09:34:15
【问题描述】:

今天我发现自己在 CakePHP 中有一个奇怪的行为。

我想要存档的是更新数据库中的列以反映上次查看的日期。当使用与标准时间戳事件(如创建、修改等)不同的列时,可以使用“touch()”来完成此操作。

  • 我想要什么:我想在 页面。
  • 发生了什么:当前日期时间戳显示在 页面。

我在这里看到的奇怪行为是:在我将实体设置为视图变量并更新触摸“上次查看”日期后,设置的视图变量中的数据反映了这种变化。

设置实体到视图的代码:

// get the request entity with the ID:
$request = $this->Requests->get($request_id);

// set the entity to the $request view variable:
$this->set('request', $request);

// finally update the last viewed date (database column name: 'opened'):
$this->Requests->touch($request, 'Requests.opened');
$this->Requests->save($request);

为什么$request视图变量会反映设置变量后执行的触摸变化?

【问题讨论】:

    标签: php cakephp view timestamp entity


    【解决方案1】:

    来自manual

    从 PHP 5 开始,对象变量不包含对象本身 值了。它只包含一个对象标识符,它允许 对象访问器来查找实际对象

    为了达到你想要的,你应该做的

    // set the entity to the $request view variable:
    $this->set('request', clone $request);
    

    但也许可以考虑将之前的“最后查看”日期而不是整个克隆实体传递给视图

    【讨论】:

    • 我需要整个请求实体,所以理论上应该没问题。我现在要测试它,感谢您的回复:) - 您的答案似乎有效!非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2012-08-08
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    相关资源
    最近更新 更多