cakePHPのデータベースについて勉強中の者です.
多対多のリレーションシップについて質問です.
現在cakePHP公式のウェブページのチュートリアルに沿って多対多のデータベースについて学習しています.
参考URL http://book.cakephp.org/2.0/ja/models/associations-linking-models-together.html#hasandbelongstomany-habtm
しかし,このページの通りにプログラムを書いたところ,同じように動作せず困惑しています.
以下が上記のページに記載されている内容です.
php
1class Recipe extends AppModel { 2public $hasAndBelongsToMany = array( 3'Ingredient' => 4array( 5'className' => 'Ingredient', 6'joinTable' => 'ingredients_recipes', 7'foreignKey' => 'recipe_id', 8'associationForeignKey' => 'ingredient_id', 9'unique' => true, 10'conditions' => '', 11'fields' => '', 12'order' => '', 13'limit' => '', 14'offset' => '', 15'finderQuery' => '', 16'with' => '' 17) 18); 19}
//$this->Recipe->find() を呼び出した時の戻り値 Array ( [Recipe] => Array ( [id] => 2745 [name] => Chocolate Frosted Sugar Bombs [created] => 2007-05-01 10:31:01 [user_id] => 2346 ) [Ingredient] => Array ( [0] => Array ( [id] => 123 [name] => Chocolate ) [1] => Array ( [id] => 124 [name] => Sugar ) [2] => Array ( [id] => 125 [name] => Bombs ) ) )
上記のページには詳しく書かれていませんが,以下のデータベースとモデルを作成しました.
データベース
recipeテーブル
Ingredientテーブル
ingredients_recipesテーブル
モデル
Recipeモデル
また,上記のような配列でデータを表示する為にrecipeコントローラには
$this->set('data', $this->Recipe->find('all'))
recipeビューには
<pre><?php print_r($data); ?></pre>を記述しています.
そして作成したページにアクセスすると以下のエラーが表示されてしまいました.
Fatal Error Error: Call to a member function schema() on a non-object File: C:\xampp\htdocs\cake\lib\Cake\Model\Model.php Line: 3720
そこで,モデルのプログラムに記載されている
'with' => '' の部分を //'with' => ''
とコメントアウトすると,以下の様に配列は表示されたのですが,ingredients_recipesテーブルのデータがingredientsテーブルとくっついて表示されてしまいました.
Array ( [Recipe] => Array ( [id] => 2745 [name] => Chocolate Frosted Sugar Bombs [created] => 2007-05-01 10:31:01 [user_id] => 2346 ) [Ingredient] => Array ( [0] => Array ( [id] => 123 [name] => Chocolate [IngredientsRecipe] => Array //この部分が表示されてしまう. ( [id] => 1 [recipe_id] => 2745 [Ingredient_id] => 123 ) ) [1] => Array ( //以下略
今回表示させる必要のないIngredientsRecipeテーブルの情報まで表示されてしまいますが,一応多対多の結合はできているので問題はありません.
しかし,なぜ公式のやり方が動かないのか,また,私なりのやり方でなぜ関係ないテーブルまで表示されてしまうのか,回答をよろしくお願いいたします.
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/11/27 13:53