在不应该有任何相关的情况下查找(null)相关项

时间:2014-01-07 02:03:28

标签: php cakephp

我正在开发我的第一个CakePHP项目。在我对“项目”的烘焙视图中,有一个“相关”div显示“相关项目”。

检查'Project'数组是否为空:

<div class="related">
    <h3><?php echo __('Related Projects'); ?></h3>
<?php if (!empty($item['Project'])): ?>
    <dl>
      ...

看到'项目'db表现在是空的,我认为这将是空的。但是,我在$item['Project']

中得到了这个
["Project"]=> array(7) { 
    ["id"]=> NULL 
    ["item_id"]=> NULL
    ["title"]=> NULL
    ...
} 

我可以通过检查NULL id来解决这个问题,但我想避免解决方法并以Cake方式做事。

控制器:

public function view($id = null) {
    if (!$this->Item->exists($id)) {
        throw new NotFoundException(__('Invalid item'));
    }
    $options = array('conditions' => array('Item.' . $this->Item->primaryKey => $id));
    $this->set('item', $this->Item->find('first', $options));
}

型号:

public $hasOne = array(
    'Project' => array(
        'className' => 'Project',
        'foreignKey' => 'item_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);

1 个答案:

答案 0 :(得分:1)

执行$ hasOne并因此直接左连接时这是正常的。 它将使用空值填充那些相关字段 - 就像mysql一样。

然后检查该记录的ID:

if (!empty($item['Project']['id']) {}
相关问题