2012-02-16 49 views
1

我對外鍵字段有問題:我創建了一個categories表,其中MySQLWorkbench1:n關係鏈接到另一個表:Articles 。它似乎工作,因爲在Articles,有一個categories_id「INT」字段。cakePhp和一個外鍵:我不能在視圖中寫外鍵

我烘烤了整個項目,一切工作正常,除了這個外鍵:而不是輸入,會收到「號碼」我會寫指定categories_id號碼,有一種空的「選擇」(列表)沒有包含任何內容,所以我不能在我的數據庫中輸入任意數量爲categories_id領域:

這裏的形象: my categories input

,如果我嘗試「力量」,並增加了「文章」(所以沒有類別),存在此錯誤:

Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (ecommerce . articles , CONSTRAINT fk_articles_categories FOREIGN KEY (categories_id) REFERENCES categories (id) ON DELETE NO ACTION ON UPDATE NO ACTION)

這是我的add.ctp文件(它是寫inputcategories_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); 
?> 

回答

1

這是由於命名慣例..如果你的表被稱爲categories那麼forei在articles中的gn鍵應該是category_id(單數)並且該模型必須被稱爲Category。控制器應傳遞給視圖名爲「$類別」(plurar)

$this->set('categories',$this->Article->Category->find('list'))

變量和在視圖中輸入已爲:

echo $this->Form->input('category_id');

不要忘記更改模型中的外鍵

希望這有助於:)

+0

「如果您的模型被稱爲Categories」=>您的意思是'Category'(singular)or'table' instead of'model' – mark 2012-02-16 10:37:58

+0

大聲笑..對不起,我會糾正 – pleasedontbelong 2012-02-16 12:31:29

+0

@pleasedontbelong:謝謝,我應該在哪裏放這個:'$ this-> set('categories',$ this - >文章 - >分類 - > find('list'));'?在'ArticlesController'>'add'中?它不起作用(因爲在非對象上調用「find」)。任何其他想法?你能解釋一下爲什麼你會打電話給「查找列表」嗎?再次感謝 – Paul 2012-02-16 22:38:46