我有一個模型「Catgeory」具有與自身與相同型號的外鍵的CakePHP HABTM關係
public $hasAndBelongsToMany = array(
'SubCategory' => array(
'className' => 'Category',
'joinTable' => 'categories_subcategories',
'foreignKey' => 'category_id',
'associationForeignKey' => 'subcategory_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
一個HABTM關係這是我用來保存類別代碼。我想建立一個關係,使得這一類的父($ ID)的子
$this->Category->create();
$c["Category"]["title"] = $this->request->data["title"];
$c["SubCategory"]["CategoriesSubcategory"]["category_id"] = $id;
的結構似乎我的權利,但這並不創建關係。然而,如果我嘗試並使用
$c["SubCategory"]["CategoriesSubcategory"]["subcategory_id"] = $id;
這是行得通的,但父母和孩子是錯誤的方式。所以這暗示了ForeignKey和AssociationForeignKey是錯誤的。所以,我當時在我的關係改變他們身邊:
public $hasAndBelongsToMany = array(
'SubCategory' => array(
'className' => 'Category',
'joinTable' => 'categories_subcategories',
'foreignKey' => 'subcategory_id',
'associationForeignKey' => 'category_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
這意味着現在的關係得到妥善保存,但是,我認爲這種關係是南轅北轍,因爲當我的findAll類別,孩子們不再來通過在結果中。
任何想法,我錯了嗎?我是否在保存錯誤的東西?我是否需要創建模型子類?
您是否考慮過使用[樹行爲](http://book.cakephp.org /2.0/en/core-libraries/behaviors/tree.html)?它可能更適合你的目的。 編輯:哎呀,剛看到比賽帕提到它已經在下面。 – 2013-05-09 16:11:38