cakephp - 应该返回模型的 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>
解决方案
推荐阅读
- android - 构建失败:后向分支 70 上存在未初始化的对象
- java - 使用 Java 11 启动弹性搜索 5.0.1 时出现 AccessControlException
- camunda - Camunda 不包含任何历史记录
- aggregation - 分类变量的聚合
- java - 我正在尝试构建 url 但出现异常
- awk - 使用 awk 过滤最后 100 行的日志
- css - 如何为具有相同类名的嵌套 div 设置样式?
- asp.net-mvc - Html.DropdownListFor 未在 Internet Explorer 11 中提交所选项目
- c++ - 使用 std::filesystem 输出作为 LPCWSTR
- javascript - 哪个单元测试设置是正确的?两个测试是否都在检查功能是否正确并正常工作?