i’ve got a problem with a foreign key field : i created a categories table with MySQLWorkbench, which is linked by a 1:n relation to another table : Articles. It seems to work, because in Articles, there is a categories_id “INT” field .
I baked the whole project, everything works fine, except this foreign key : instead of an input that would receive the “number” i would write to specify the categories_id number, there is a kind of empty “select” (list) that contains nothing, so i cannot enter any number for the categories_id field in my database :
here’s the image :

If i try to “force” and add an “article” (so without the category), there is this error :
Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
ecommerce.articles, CONSTRAINTfk_articles_categoriesFOREIGN KEY (categories_id) REFERENCEScategories(id) ON DELETE NO ACTION ON UPDATE NO ACTION)
And here’s my add.ctp file (it is written input for the categories_id, so i don’t know what to change) :
<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');
?>
Thanks for your help
EDIT:
here’s what i added :
class Article extends AppModel {
var $belongsTo = array(
'Category' => array(
'className' => 'Category',
'foreignKey' => 'category_id'
)
);
}
and :
class Category extends AppModel {
var $hasMany = array(
'Article' => array(
'className' => 'Article',
'foreignKey' => 'category_id'
)
);
}
and in the controller (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);
but in my view, pr($cat) returns an empty Array…
<?php
echo $this->Form->input('nom');
echo $this->Form->input('prix');
echo $this->Form->input('category_id', array('option'=>$cat));
pr($cat);
?>
It’s because of the naming convention.. if your table is called
categoriesthen the foreign key inarticlesshould becategory_id(singular) and the model must be calledCategory. The controller should pass to the view a variable called ‘$categories’ (plurar)$this->set('categories',$this->Article->Category->find('list'))and the input in the view has to be:
echo $this->Form->input('category_id');don’t forget to change the foreign key in the model too
Hope this helps 🙂