加入Pivot tabel Laravel

时间:2016-08-19 10:59:58

标签: php database laravel-5.2

我有以下表格:

食物:

  • Foodid(PK)
  • FoodName
  • FoodImage
  • 描述

分类

  • CATEGORY_ID(PK)
  • 类别名称

餐厅

  • RES_ID(PK)
  • ResName
  • 地址

category_food_restaurant

  • CATEGORY_ID(FK)
  • Food_id(FK)
  • RES_ID(FK)

现在我想根据类别名称显示食物项目。为此,我将查询显示为:

$Category = DB::table('Food')
                ->select('Food.Food_id','Food.FoodName',
                        'Food.FoodImage','Categories.CategoryName')
                ->join('Categories','Categories.Category_id',
                        '=','category_food_restauarant.Category_id')
                ->where('Categories.CategoryName', 
                        '=','Breakfast')->get();

但是这给了我错误:

  

SQLSTATE [42S22]:未找到列:1054'on子句'中的未知列'Food.Category_id'(SQL:选择FoodFood_idFood。{{1 {},FoodNameFoodFoodImage Categories来自CategoryName Food Categories CategoriesCategory_id } = FoodCategory_id其中CategoriesCategoryName =早餐)。

问题在哪里。如何使用这些表格根据类别显示食物项目?

1 个答案:

答案 0 :(得分:0)

您正在加入Food表和Categories表,但它们之间没有任何关系。所以你必须通过category_food_restaurant加入这两个表。以下应该有效:

DB::table('category_food_restaurant')
            ->select('Food.Food_id','Food.FoodName',
                    'Food.FoodImage','Categories.CategoryName')
            ->join('Categories','Categories.Category_id',
                    '=','category_food_restaurant.Category_id')
            ->join('Food','Food.Food_id',
                    '=','category_food_restaurant.Food_id')
            ->where('Categories.CategoryName', 
                    '=','Breakfast')->get();