在laravel中联接多个表

时间:2019-11-14 11:10:46

标签: laravel

我需要在laravel中左连接三个表。我在两个表中为id提供了相同的名称以进行连接,但是我没有得到正确的输出。我没有得到整个id值,而只是得到了连接的ids

$products = DB::table('categories')
        ->leftjoin('subcategories', 'categories.category_id', '=', 'subcategories.category_id')
        ->leftjoin('products', 'products.subcat_id', '=', 'subcategories.subcat_id')
        ->get()->toArray();

Ouput

id  Category    Subcategory   Product
1   Lunch       Chinese       noodles
1   Lunch       Chinese       pizza
2   Breakfast   Indian        dosa
2   Breakfast   Indian        idly
    Dinner      
    Meals       
    xyz 

1 个答案:

答案 0 :(得分:0)

您应该使用select like

$products = DB::table('categories')
    ->leftjoin('subcategories', 'categories.category_id', '=', 'subcategories.category_id')
    ->leftjoin('products', 'products.subcat_id', '=', 'subcategories.subcat_id')
    ->select('products.id as productId', 'categories.id as categoriesId', 'subcategories.id as subCategoryId', 'categories.Category as Category', 'categories.Subcategory as Subcategory', 'product.name as product')
    ->get()->toArray();

如果要获取所有产品,我建议您首先使用产品模型,并且在急于加载时,应该获取所有其他关系值。