【问题标题】:Cakephp How to set find() to return blank array instead of empty array when no result matchedCakephp如何设置find()在没有结果匹配时返回空白数组而不是空数组
【发布时间】:2014-02-10 11:05:28
【问题描述】:

默认情况下,cakephp 将在 find() 上返回空数组。 但是如何将其设置为显示为空白数组。

例如:

$customer = $this->Transaction->Customer->find(--conditions to return 0 result.--)

我希望它像这样显示为 空白数组

array('Customer' => array('customer_id'=>null, 'name'=>null, 'lastname'=>null))

不只是空的一个像

array()null

因为我总是看到错误显示$customer['Customer']['name'] 是未定义的索引。而且我不喜欢每次都使用isset()is_null() 进行检查。

【问题讨论】:

    标签: arrays cakephp find


    【解决方案1】:

    在模型中使用 afterFind 回调方法。像这样的:

    public function afterFind($results, $primary = false) {
        if (empty($results)) {
            $results = array('Customer' => array('customer_id'=>null, 'name'=>null, 'lastname'=>null))
        }
        return $results;
    }
    

    http://book.cakephp.org/2.0/en/models/callback-methods.html

    【讨论】:

      【解决方案2】:

      如果你真的想要/需要这样做,你可以使用类似的东西:

      $default = array('Customer' => array('customer_id' => null, 'name'=>null, 'lastname' => null));
      $customer = $this->Transaction->Customer->find(...)
      $customer = array_merge($default, $customer);
      

      这样,如果结果为空,它将使用您的默认值。

      但是,这不是一个好的做法,因为您最终可能会在页面中显示"Welcome, NULL"。您应该在视图中使用if (!empty($customer)) ...

      另外,在这个例子中,你使用的是find->('first') 吗?

      【讨论】:

      • 是的,我正在使用 find->('first') .and find->('all')
      • 我的回答可以满足您的需要吗?如果没有,您可以将您正在使用的代码粘贴到视图中吗?
      • 您的回答对我的问题来说没问题,但是每次更新客户表时必须更改默认数组。我会想办法解决这个问题并合并数组,谢谢。
      猜你喜欢
      • 2015-10-22
      • 1970-01-01
      • 2016-06-27
      • 2012-12-23
      • 2023-01-10
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多