我有3张桌子。三张桌子上的Cakephp关系
- 设备hasOne DeviceGroup
- 集团的hasMany设备
- DeviceGroup(属于设备及集团)
现在,如果我这样做$this->Device->find('all');
它给我的结果是:
Device => array
DeviceGroup => array
现在我也想从Group表中获取值,我该怎么做?
我有3张桌子。三张桌子上的Cakephp关系
现在,如果我这样做$this->Device->find('all');
它给我的结果是:
Device => array
DeviceGroup => array
现在我也想从Group表中获取值,我该怎么做?
有几种方法可以做到这一点。
这可能是这么简单:
$this->Device->find('all', array('recursive' => 2));
但是,这是相当沉重的资源和浪费的,如果你有一个会得到自动检索等车型。
另一种方法是将集团类添加到您的设备型号:
var $hasOne = array(
'DeviceGroup' => array(
'className' => 'DeviceGroup',
'foreignKey' => 'device_group_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => ''
),
'Group' => array(
'className' => 'Group',
'foreignKey' => false,
'dependent' => false,
'conditions' => 'Group.id = DeviceGroup.group_id',
'fields' => '',
'order' => ''
)
);
这可能是有问题的,当你再试着从另一个模型自动包括当你已经有设备的集团的关系做一个查找集团在寻找。所以最好把它命名为$ hasOne中的其他东西,比如'DeviceGroupGroup',这很痛苦。
我的首选方法是使中可容纳的行为(我这样做是app/app_model.php
使所有模型自动中可容纳启用):
class AppModel extends Model {
var $actsAs = array('Containable');
}
然后,而不必组添加到您可以在设备型号做到这一点:
$this->Device->find(
'all',
array(
'contain' => array('DeviceGroup', 'Group'),
'recursive' => 2,
)
);
这样一来,即使你是比较深递归,你只检索你真正想要的车型,如果你同时使用'fields'
参数上您find
你会一直拉扯。
。谢谢。 – vibha
DeviceGroup表上是否有额外的字段?如果不是,可以将其模拟为您的第二个解决方案的HABTM关系 – pleasedontbelong