我有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