我想保存產品的多個類別。cakephp hasmany形式數據
我有型號:
Category.php
public $hasAndBelongsToMany = array(
'Product' => array(
'className' => 'Product',
'joinTable' => 'product_categories',
'foreignKey' => 'category_id',
'associationForeignKey' => 'product_id',
'unique' => 'keepExisting',
)
);
Product.php
public $hasMany = array(
'ProductCategory' => array(
'className' => 'ProductCategory',
'foreignKey' => 'product_id',
'dependent' => false,
),
ProductCategory.php
public $belongsTo = array(
'Product' => array(
'className' => 'Product',
'foreignKey' => 'product_id',
),
'Category' => array(
'className' => 'Category',
'foreignKey' => 'category_id',
)
);
所以在產品/添加視圖我通過添加一組類別的複選框:
echo $this->Form->input('ProductCategory.category_id',array(
'label' => __('Category',true),
'type' => 'select',
'multiple' => 'checkbox',
'options' => $categories
));
但是,這會產生與名一組輸入的:name="data[ProductCategory][category_id][]"
而不是name="data[ProductCategory][0][category_id]"
零被遞增。
如果他們的格式與模型和字段之間的關鍵,那麼我可以使用saveAll()? 因爲它是在我得到的格式中,我將不得不操縱請求 - >數據以將其轉換爲我希望能夠保存的表單()
我該如何解決這個問題?或者,也許我的模型設置不正確?
此外,編輯has have many data會發生什麼?如果例如我取消選中某個選項並添加另一個選項會怎麼樣?添加新蛋糕之前,蛋糕會自動刪除所有關聯的記錄嗎?
編輯。
本質上講,我問的是有沒有這樣做的更好或更快的方法,它現在的工作:
if ($this->Product->save($this->request->data)) {
$this->Product->ProductCategory->deleteAll(array('ProductCategory.product_id' => $this->Product->id));
foreach ($this->request->data['ProductCategory']['category_id'] as $cat_id) {
$this->Product->ProductCategory->create();
$this->Product->ProductCategory->set(array(
'product_id' => $this->Product->id,
'category_id' => $cat_id
));
$this->Product->ProductCategory->save();
}
}
線顯示:[產品型號] [0] [字段名]用於saveAll()以處理多個記錄。如果我只能通過FormHelper以這種方式輸出複選框輸入... – charliefarley321
是的。 對不起,但你爲什麼不試試呢?這個聲音不像一個活的環境,所以只需要清空數據庫表,添加產品,點擊一些類別,點擊提交併查看數據庫。 如果它不適用於您的代碼,請查看上面提供的文檔鏈接。無論如何,你至少應該在用cakephp開發之前閱讀這個部分。對於任何使用cakephp應用程序的工作,超過80%的工作至關重要。 – func0der
如果您對您的觀點持懷疑態度,請閱讀一些測試視圖,以瞭解Cake如何形成代碼。 –