2017-12-09 4 views
0

質問に正確に名前を付ける方法がわからず、より良いタイトルを得ることができなかったため、以前に聞いたことのある同じ問題を多く検索することができませんでした。内部選択をpdoクエリの中に入れる方法は?

私のデータベースには1対多の関係があり、データはいくつかのテーブルに分散しています。

public function get_recipe_data($id){ 
    $sth = $this->db->prepare('SELECT * FROM 
           recipe as recipe 
           LEFT JOIN recipe_introduction as introduction 
           ON recipe.id = introduction.recipe_id 
           LEFT JOIN recipe_ingredients as ingredients 
           ON recipe.id = ingredients.recipe_id 
           LEFT JOIN recipe_ingredients_notes as notes 
           ON recipe.id = notes.recipe_id 
           LEFT JOIN recipe_macros as macros 
           ON recipe.id = macros.recipe_id 
           WHERE recipe.id = :id 
    '); 
    $sth->bindValue(':id', $id, PDO::PARAM_INT); 
    $sth->execute(); 

    return $sth->fetch(PDO::FETCH_ASSOC); 
} 

public function convertCategoryId($category_id){ 
    $sth = $this->db->prepare('SELECT name FROM recipe_categories WHERE id = :category_id'); 
    $sth->bindValue(':category_id', $category_id, PDO::PARAM_INT); 
    $sth->execute(); 

    return $sth->fetch(PDO::FETCH_ASSOC); 
} 

レシピテーブルには、カテゴリ名のIDを持ち、別のテーブルを参照する列があります。

レシピテーブル

+----+-------+-------------+ 
| id | title | category_id | 
+--------------------------+ 
| 1 | ... |  1  | 
+----+-------+-------------+ 
| 2 | ... |  3  | 
+----+-------+-------------+ 

私は

recipe_categories

+----+------------+ 
| id | name | 
+----+------------+ 
| 1 | breakfast | 
+----+------------+ 
| 2 | lunch | 
+----+------------+ 
| 3 | dinner | 
+----+------------+ 
| .. | ...  | 
+----+------------+ 

は今、私は上記の最初のクエリから結果を返すために抱えているこの他のテーブルを持っています、一度私はそれを持っている、私はcategory_iを渡すクラスの別のメソッドを実行します最初のクエリのdを入力し、それをrecipe_categoriesにマッチさせますが、それは非常に効率的ではありません。

名前を最初のクエリから直接選択できる方法はありますか?

+0

これは特にPDOとは何の関係もなく、純粋なSQLの質問です。あなたは明らかにJOINsが既に何であるかを知っているので、idテーブルを使って名前を取得するために、カテゴリテーブルに参加することから何が止まったのかを説明してください...? – CBroe

+1

@CBroe私は今、 "恥ずかしそう"をしています。完全に恥ずかしいです。袋を打つ必要があります。あなたは正しかった、私はちょうど最初にテーブルに参加する必要があります。ありがとう。 – Craig

答えて

0

カテゴリテーブルをレシピテーブルに追加するだけで、単一のクエリでカテゴリ名にアクセスできます。

SELECT 
     * 
FROM recipe AS recipe 
INNER JOIN recipe_categories AS rcat ON recipe.category_id = rcat.id 
LEFT JOIN recipe_introduction AS introduction ON recipe.id = introduction.recipe_id 
LEFT JOIN recipe_ingredients AS ingredients ON recipe.id = ingredients.recipe_id 
LEFT JOIN recipe_ingredients_notes AS notes ON recipe.id = notes.recipe_id 
LEFT JOIN recipe_macros AS macros ON recipe.id = macros.recipe_id 
WHERE recipe.id = id 

注意。 PHPユーザーの間では、「選択*」を使用するのが一般的なようですが、戻りたいと思う各列を指定し、偶然にしないでください。

関連する問題