I’m using cakephp 2.1.3 and I have a table Ingredients and a table IngredientAliases
I want that in my page index in Ingredient when I select an IngredientAlias I want to see the IngredientAlias and some fileds of Ingredients
But I don’t know if I have to make two query into my controller or only to set ingredients_id the id and cakephp in automatically retrieve me the data. Now I make two query in my controller but I don’t know if it’s the best way
$this->set('ingredient', $this->Ingredient->read()); $this->set('ingredient_alias',$this->Ingredient->IngredientAlias->read());
Here is my tables:
class Ingredient extends AppModel {
public $name = 'Ingredient';
public $useTable = 'ingredients';
public $belongsTo = 'User';
public $hasMany = array (
'IngredientAlias' => array (
'className' => 'IngredientAlias',
'foreignKey' => 'ingredient_id'
)
);
}
class IngredientAlias extends AppModel {
public $name = 'IngredientAlias';
public $useTable = 'ingredient_aliases';
public $belongsTo = array(
'Ingredient' => array(
'className' => 'Ingredient',
'foreignKey' => 'ingredient_id'
)
);
}
And here is my IngredientsController (I have changed the routes to putt alias into my arguments and it’s working)
public function edit ($alias) {
$ing = $this->Ingredient->IngredientAlias->find('first', array(
'conditions' => array('IngredientAlias.alias' => $alias)));
$this->Ingredient->IngredientAlias->id= $ing['IngredientAlias']['id'];
$this->Ingredient->IngredientAlias->set('ingredient_id',$ing['IngredientAlias']['ingredient_id']);
$this->Ingredient->id= $ing['IngredientAlias']['ingredient_id'];
if (!$this->Ingredient->IngredientAlias->exists()) {
throw new NotFoundException ('Nessuna corrispondenza trovata per questo ingrediente');
}
if (!$alias) {
$this->set('flash_element','error');
$this->Session->setFlash ('Ingrediente non valido');
}
$this->Ingredient->recursive = 2;
$this->set('ingredient', $this->Ingredient->read());
$this->set('ingredient_alias',$this->Ingredient->IngredientAlias->read());
}
Based on the relations you described and if you have a
ingredient_idkey in youringredient_aliasestable if you call:You would get the Ingredient record specified by $id with all it’s associated IngredientAlias records in an array structure similar to the following:
The IngredientAlias array sub-structure is indexed because of the hasMany relation.
If you’re not seeing the associated IngredientAlias records then check your Model’s recursive property:
If it equals -1 then only the Ingredient Model data will be fetched. Check out what the other recursive values do in the link I provided.
If you want to go the other way around you should go through the IngredientAlias model:
will provide the specified in the CONDITIONS IngredientAlias record with it’s connected Ingredient record. The Ingredient record will be only one because of the
IngredientAlias belongsTo Ingredientrelation.