一个查询从多个表中检索值

One query to retrieve values from multiple tables

我一直在尝试从多个 tables 中检索数据,在我遇到使用枢轴 tables(或 link tables 之间的多对多关系 tables).

到目前为止,我可以很容易地从每个 table 中获取数据,但我只需要进行一次查询,它将获取我需要的所有数据。

表格 = 产品、详情、类别,product_category(这个是支点table)

product_category = product_id | category_id(这些列中的每一列都引用了 id - product_id 引用了产品,category_id 引用了类别)

获取查询的代码:

$products = DB::table('products')
                    ->join('details', 'products.id', '=', 'details.product_id')
                    ->leftJoin('product_category', function($join) {
                        $join->on('products.id', '=', 'product_category.product_id');
                    })
                    ->select('products.*', 'details.*', 'product_category.*')
                    ->orderBy('products.created_at', 'desc')
                    ->paginate(10);

然后在索引页上,我可以在 foreach 循环中获取所有数据,但是有一个小问题 - 我只能获取 product_category 的列,换句话说,只能获取 category_id 的引用categories.id - 但我需要从类别 table 中获取这些值。

请不要给我文档或类似的东西,我每次问问题之前都会做很多研究并阅读至少一打类似的问答,但有时我需要另一种观点才能得到解决方案并了解其工作原理。感谢您的帮助。

问题是覆盖了您的专栏信息。

您可以这样修改您的查询:

$query = DB::table('product_category as pc')
    ->leftJoin('products as p', 'p.id', 'pc.product_id')
    ->join('details as d', 'd.product_id', 'p.id')
    ->select('p.id as product_id', 'p.name as product_name', 'd.id as details_id', .......) // <-- you need to select field whichever you want. table.* is applicable if tables have different column names.