2012-02-16 47 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