我使用一個單一的「類別」表中,並且具有parent_id
字段引用表中的任何其他種類的風扇。
這允許您在單個表中包含所有線程類別......您的「類別組」只是任何在其parent_id字段中沒有數據的類別行。
實例數據
id name parent_id category_count
1 appliances null 1
2 dogs null 1
3 couch 1 0
4 pitbull 2 0
5 games null 0
//...
基本上, '類別' 是關係到本身 - 這裏的模型關聯: (參考:在CakePHP book的3rd code example here)
class Category extends AppModel {
public $belongsTo = array(
'Parent' => array(
'className' => 'Category',
'foreignKey' => 'parent_id',
'counterCache' => true
)
);
public $hasMany = array(
'Children' => array(
'className' => 'Category',
'foreignKey' => 'parent_id'
)
);
//...
}
class Item extends AppModel {
public $belongsTo = array('Category');
//...
}
你也可以做Item hasAndBelongsToMany Category
而不是belongsTo
,如果你願意 - 取決於你的設置。
附加信息:
CounterCache:有關CakePHP的counterCache,go here更多信息。
find->螺紋:使用這種方法,你可以輕鬆地獲得通過嵌套數據CakePHP的find->螺紋(click here for more info about this)
謝謝你的@Sevak我增加了第四臺處理類別組。什麼是(FK)和(PK)btw? – MotoX 2012-03-13 13:38:32
PK =主鍵; FK =外鍵(=引用表的主鍵)。 – dgw 2012-03-13 13:52:57
是啊@dgw是正確的...... – 2012-03-14 04:06:19