我對外鍵字段有問題:我創建了一個categories
表,其中MySQLWorkbench
與1:n
關係鏈接到另一個表:Articles
。它似乎工作,因爲在Articles
,有一個categories_id
「INT」字段。cakePhp和一個外鍵:我不能在視圖中寫外鍵
我烘烤了整個項目,一切工作正常,除了這個外鍵:而不是輸入,會收到「號碼」我會寫指定categories_id
號碼,有一種空的「選擇」(列表)沒有包含任何內容,所以我不能在我的數據庫中輸入任意數量爲categories_id
領域:
這裏的形象:
,如果我嘗試「力量」,並增加了「文章」(所以沒有類別),存在此錯誤:
Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
ecommerce
.articles
, CONSTRAINTfk_articles_categories
FOREIGN KEY (categories_id
) REFERENCEScategories
(id
) ON DELETE NO ACTION ON UPDATE NO ACTION)
這是我的add.ctp
文件(它是寫input
爲categories_id
,所以我不知道是什麼改變):
<div class="articles form">
<?php echo $this->Form->create('Article');?>
<fieldset>
<legend><?php echo __('Add Article'); ?></legend>
<?php
echo $this->Form->input('nom');
echo $this->Form->input('prix');
echo $this->Form->input('categories_id');
?>
感謝您的幫助
編輯:
這是我加了什麼:
class Article extends AppModel {
var $belongsTo = array(
'Category' => array(
'className' => 'Category',
'foreignKey' => 'category_id'
)
);
}
和:
class Category extends AppModel {
var $hasMany = array(
'Article' => array(
'className' => 'Article',
'foreignKey' => 'category_id'
)
);
}
,並在控制器(add()
):
public function add() {
//$this->set('categories',$this->Article->Category->find('all'));
//$c = $this->Article->Category->find('all', array("recursive"=>-1, 'fields'=>array('id', 'nom')));
$c = $this->Article->Category->find('list');
$this->set('cat', $c);
,但在我看來,pr($cat)
返回一個空數組...
<?php
echo $this->Form->input('nom');
echo $this->Form->input('prix');
echo $this->Form->input('category_id', array('option'=>$cat));
pr($cat);
?>
「如果您的模型被稱爲Categories」=>您的意思是'Category'(singular)or'table' instead of'model' – mark 2012-02-16 10:37:58
大聲笑..對不起,我會糾正 – pleasedontbelong 2012-02-16 12:31:29
@pleasedontbelong:謝謝,我應該在哪裏放這個:'$ this-> set('categories',$ this - >文章 - >分類 - > find('list'));'?在'ArticlesController'>'add'中?它不起作用(因爲在非對象上調用「find」)。任何其他想法?你能解釋一下爲什麼你會打電話給「查找列表」嗎?再次感謝 – Paul 2012-02-16 22:38:46