我正在使用 cakephp 2.1.3 并且我有一个表成分和表成分别名当我选择成分别名时我希望在我的页面索引中的成分中我想查看成分别名和一些成分文件但我不知道是否我必须对我的控制器进行两次查询,或者只设置成分 ID 和 cakephp 自动检索我的数据。现在我在我的控制器中做了两个查询,但我不知道这是否是最好的方法
$this->set('ingredient', $this->Ingredient->read()); $this->set('ingredient_alias',$this->Ingredient->IngredientAlias->read());
这是我的桌子:
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'
)
);
}
这是我的 IngredientsController (我已经将 putt alias 的路径更改为我的参数并且它正在工作)
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());
}