我正在尝试学习CakePHP,并试图复制我可以用标准PHP和MySQL做的事情。
我有一个包含事件信息的event
表和一个包含要在每个事件页面上显示的项目符号列表条目的list_items
表。我还有一个列出地点(id、event_id和name)的venue
表,最后还有一个将事件和地点连接在一起的instance
表-它由id、event_id、venue_id和date组成。
我已经按照我认为的方式关联了这些表:
class Event extends AppModel{
public $hasMany = array(
'ListItem',
'Instance'
);
}
项目符号列表项目:
class ListItem extends AppModel{
public $belongsTo = array(
'Event'
);
}
实例:
class Instance extends AppModel{
public $belongsTo = array(
'Event'
);
public $hasOne = array(
'Venue'
);
}
地点:
class Venue extends AppModel{
public $belongsTo = array(
'Instance'
);
并且事件控制器具有基于ID来查找事件的查询:
public function view($id = null){
if (!$id){
throw new NotFoundException(__('Invalid Course'));
}
$event = $this->Event->findById($id);
if (!$event){
throw new NotFoundException(__('Invalid event'));
}
$this->set('event',$event);
}
这些关联是正确的吗?我希望能够在地点旁边显示实例日期--目前我可以输出日期没有问题,但地点对我来说并不重要。
发布于 2014-06-20 21:30:48
可能是因为递归性不够深。要更改这一点,您可以执行以下操作:
最简单但最糟糕的方法是在find之前更改递归性:
$this->Event->recursive = 2; //change it according to the deepness you want
这只会根据分配的深度检索所有关系,但不能排除不需要的关系。
或者,更高级但更丰富的方法,添加Containable
行为并自己创建递归性。在模型的开头添加以下行为:
public $actsAs = array('Containable');
在你的find函数中:
$event = $this->Event->find('first', array(
'conditions' => array('id' => $id),
'contain' => array(
'ListItem',
'Instance' => array(
'Venue'
)
)
));
与recursive
相比,Contain
的优势在于您可以控制find
查询关系的各个方面,因此您可以只检索所需的数据。因此,强烈建议您使用Containable
行为作为
有关更多信息,请参阅文档:http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html
https://stackoverflow.com/questions/24327763
复制相似问题