Php 当存在';没有任何关系
我正在做我的第一个CakePHP项目。在我烘焙的“Item”视图中,有一个“related”div,显示“relatedprojects” 它检查“项目”数组是否为空:Php 当存在';没有任何关系,php,cakephp,Php,Cakephp,我正在做我的第一个CakePHP项目。在我烘焙的“Item”视图中,有一个“related”div,显示“relatedprojects” 它检查“项目”数组是否为空: <div class="related"> <h3><?php echo __('Related Projects'); ?></h3> <?php if (!empty($item['Project'])): ?> <dl> .
<div class="related">
<h3><?php echo __('Related Projects'); ?></h3>
<?php if (!empty($item['Project'])): ?>
<dl>
...
我可以通过检查空id来解决这个问题,但我希望避免这种变通方法,并以简单的方式做事
控制器:
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' => ''
)
);
型号:
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' => ''
)
);
这在执行$hasOne时是正常的,因此直接进行左连接。 它将用空值填充这些相关字段——就像mysql一样 检查该记录的id,然后:
if (!empty($item['Project']['id']) {}
谢谢你提供的信息。有没有办法让它不填充,除非有匹配项?将其更改为$hasMany(即使它只有一个或没有)有意义吗?不,没有意义。我已经给了你答案。要么整个记录是一个空数组(如果没有主记录),要么需要使用上面的检查。