我有一个有一些关系的数据库。在这个例子中我有两个表:
activity_ingredients ingredient_aliases
--------------- ---------------
id id
ingredient_id ingredient_id
我想在我的模型中设置一个条件,以通过字段“ingredient_id”连接表。我已经在这种模式下完成了:
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
)
);
}
如果我写这段代码给我一个这样的错误:
未找到列:1054“where 子句”中的未知列“ActivityIngredients.ingredient_id”
但是,如果我写 hasOne 而不是 hasMany,它不会返回任何错误并且是完美的。但是我的关系是hasMany..为什么?
为了检索数据,我对我的 UserController 进行了查询。用户通过hasMany与Activity关联,Activity与ActivityIngredients在这种模式下关联:
public $hasOne = array(
'ActivityIngredients' => array(
'className' => 'ActivityIngredients',
'conditions' => '',
'dependent' => true,
'foreignKey' => 'activity_id'
)
要检索数据,我目前正在使用此查询,但我认为我现在必须更改所有查询
$this->User->Activity->recursive = 2;
$activity = $this->User->Activity->findAllByUser_id($id);
$this->set('activity', $activity);