我有一个关系数据库。 我在这个例子中有两个表:
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'
但是如果不是hasMany我写了hasOne它不会返回任何错误并且是完美的。但我的关系是很多......为什么?
要检索数据,我会查询我的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);
答案 0 :(得分:0)
在定义模型类时,首先应该使用单数词。这意味着模型名称应为ActivityIngredient
而不是ActivityIngredients
。
虽然activity_ingredients
表中的如果ingredient_id
id是属于ingredient_aliases
表的外键。然后它应该命名为ingredient_alias_id
。同样,如果你在ingredient_aliases
表中也这样做,即外键名称为activity_ingredient_id
。那么根本就没有问题。
但是,我正在解决您的问题。请检查并验证。
然后您的代码应如下所示:
class ActivityIngredient extends AppModel{
public $name = 'ActivityIngredient';
public $useTable = 'activity_ingredients'; // if you use singular term then no need to define $useTable
public $hasMany = array (
'IngredientAlias' => array (
'className' => 'IngredientAlias',
'foreignKey' => false,
'finderQuery' => 'select * from ingredient_aliases as `IngredientAlias`
where `IngredientAlias`.`ingredient_id` = {$__cakeID__$}'
)
);
}
class IngredientAlias extends AppModel {
public $name = 'IngredientAlias';
public $useTable = 'ingredient_aliases';
public $belongsTo = array(
'ActivityIngredient' => array(
'className' => 'ActivityIngredient',
'foreignKey' => 'ingredient_id'
)
);
}
答案 1 :(得分:0)
你已经用过了
conditions'=>数组('ActivityIngredients.ingredient_id = IngredientAlias.ingredient_id')
应该是
conditions'=> array('ActivityIngredients.ingredient_id => IngredientAlias.ingredient_id')
使用以下代码
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
)
);
}
?>