首页 > 解决方案 > 应该返回模型的 Cakephp 3.6 助手被强制转换为模板中的数组

问题描述

帮手:

class QuestionHelper extends Helper
{
    protected $_defaultConfig = [];

    public function mostRecentAnswer(Question $q): ?Answer
    {
        $result = (new Collection($q->answers))->max(function($a) {
            return $a->created;
        });
        if ($result) {
            return $result;
        }
        return null;
    }
}

我想在模板中使用它来显示日期,但是使用属性访问表示法调用它会导致错误:

称呼:<td><?= h($this->Question->mostRecentAnswer($question)->created) ?></td>

错误:Notice (8): Trying to get property 'created' of non-object [APP/Template\Questions\index.ctp, line 24]

但是,将返回的对象包装在dd显示中:

称呼:dd(get_class($this->Question->mostRecentAnswer($question)))

结果:"App\Model\Entity\Answer"

在模板中使用数组访问有效:

<td><?= h($this->Question->mostRecentAnswer($question)['created']) ?></td>

这是正常行为吗?

事实证明一切正常。该通知是由于另一个问题,在不同的行项目上,没有任何关联的答案,因此返回 null。我只是在帮助器上添加了一个包装器:

public function mostRecentAnswerCreatedDate(Question $q): string
{
    $result = $this->mostRecentAnswer($q);
    if ($result) {
        return $result->created;
    }
    return 'Not yet answered';
}

并称它为

<td><?= h($this->Question->mostRecentAnswerCreatedDate($question)) ?></td>

标签: cakephphelper

解决方案


推荐阅读