我得到的结果集如下:
$something = $this->contain('First.Second.Third');
如果我在结果中有一些数据,我会正确地获得实体,但如果数据库中没有任何数据,我就会得到Null,这会导致模板中出现"获取非对象的属性"错误。我现在所做的是为每个表分配新的实体,比如:
if(!$something->first)
{
$something->first = TableRegistry::get('First')->newEntity();
$something->first->second = TableRegistry::get('Second')->newEntity();
$something->first->second->third = TableRegistry::get('Third')->newEntity();
}
当我每次得到空结果时,我该如何避免这样做?
只需在视图模板中说明这种可能的情况,就不需要任何花哨的解决方案,只需测试null
或空,或使用Entity::has()
。