私はcakephp2.1.3を使用していて、テーブルIngredientsとテーブルIngredientAliasesがあります。IngredientAliasを選択すると、Ingredientのページインデックスに表示されます。IngredientAliasとIngredientsのいくつかのファイルが表示されます。コントローラに2つのクエリを実行するか、components_idを設定するだけでidとcakephpが自動的にデータを取得します。今、コントローラーで2つのクエリを実行しますが、それが最善の方法かどうかわかりません
$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です(引数にエイリアスを置くようにルートを変更しましたが、機能しています)
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());
}