I have a database with some relations.
I have two tables in this example:
activity_ingredients ingredient_aliases
--------------- ---------------
id id
ingredient_id ingredient_id
I want to make a conditions into my model to connect the tables by the field “ingredient_id”. I have done in this mode:
class ActivityIngredients extends AppModel{
public $name = 'ActivityIngredients';
public $useTable = 'activity_ingredients';
public $hasMany = array (
'IngredientAlias' => array (
'className' => 'IngredientAlias',
'foreignKey' => false,
'conditions' => array('ActivityIngredients.ingredient_id = IngredientAlias.ingredient_id')
)
);
}
class IngredientAlias extends AppModel {
public $name = 'IngredientAlias';
public $useTable = 'ingredient_aliases';
public $belongsTo = array(
'ActivityIngredients' => array(
'className' => 'ActivityIngredients',
'foreignKey' => false
)
);
}
If I write this code give me an error like this:
Column not found: 1054 Unknown column ‘ActivityIngredients.ingredient_id’ in ‘where clause’
But if Instead of hasMany I write hasOne it doesn’t return any error and is perfect. But my relation is hasMany.. why?
To retrieve data I make a query into my UserController.
User is associated with Activity with hasMany, Activity is associated with ActivityIngredients in this mode:
public $hasOne = array(
'ActivityIngredients' => array(
'className' => 'ActivityIngredients',
'conditions' => '',
'dependent' => true,
'foreignKey' => 'activity_id'
)
To retrieve data I’m using this query at the moment but I think that I have to change all query now
$this->User->Activity->recursive = 2;
$activity = $this->User->Activity->findAllByUser_id($id);
$this->set('activity', $activity);
The first thing you should use a singular word while defining model class. It means that the model name should be
ActivityIngredientinstead ofActivityIngredients.Although if in
activity_ingredientstable ifingredient_idid is a foreign key that belongs toingredient_aliasestable. Then it should be named asingredient_alias_id. Similiarly if you would do this same iningredient_aliasestable, i.e. the foreign key name would beactivity_ingredient_id. Then there will be no problem at all.However, I am giving a solution to your problem. Kindly check and verify.
Then your code should looks like: