简体   繁体   English

在 Laravel 查询中难以正确连接表

[英]Difficulty properly joining tables in Laravel query

I'm having difficulty properly joining tables in L9.我在 L9 中正确加入表格时遇到困难。 This joins my products and additionalProducts tables.这将加入我的产品和 additionalProducts 表。 The mission is to get all the products that can be added with productId(x).任务是获取所有可以用productId(x)添加的产品。 I have the Product table with all the info and additonalProduct that look like this:我有 Product 表,其中包含所有信息和 additonalProduct,如下所示:

id ID product_id产品编号 additionalProductId附加产品编号
1 1个 1 1个 2 2个
2 2个 1 1个 4 4个
3 3个 2 2个 3 3个
4 4个 2 2个 5 5个

The meaning for product_id=1 I want to get all the info of the products with id 2 and 4 from 'product' table and for product_id=2 get the info of products 3 and 5. product_id=1 的含义我想从“product”表中获取 id 为 2 和 4 的产品的所有信息,product_id=2 获取产品 3 和 5 的信息。

This query is working when productId is hard coded('1' or '2') but when I tray make it dynamic for some reason I got error $productId undefined.当 productId 被硬编码('1' 或 '2')时,此查询有效,但是当我出于某种原因托盘使其动态时,我收到错误 $productId undefined。

$productId = $productsInfo[0]->product_id; (when i print it with dd it show id=1 or 2). (当我用 dd 打印它时,它显示 id=1 或 2)。 but inside the query it is undefined and I cannot understand why and how to fix it.但在查询中它是未定义的,我不明白为什么以及如何修复它。

$viewData['additionalProducts'] = DB::table('products as p')
    ->join('addtionalproducts as ap', function ($join) {
        $join->on('p.id', '=', 'ap.additionalProductId')
             ->select('p*')
             ->where('ap.product_id', '=', $productId);
    })->get();

It seems you're joining the wrong columns:看来您加入了错误的专栏:

$join->on('p.id', '=', 'ap.additionalProductId')

And I don't really understand this part either, because the WHERE clause doesn't belong there:而且我也不太理解这部分,因为WHERE子句不属于那里:

->select('p*')->where('ap.product_id', '=', $productId);

Which should rather be:哪个应该是:

$join->on('p.additionalProductId', '=', 'ap.product_id')

And watch out for spelling errors;并注意拼写错误; the question had quite few before the edit.在编辑之前这个问题很少。
Better first try without the WHERE clause to get any results, then start to limit.最好先尝试不使用WHERE子句以获得任何结果,然后再开始限制。

A join doesn't need any sub-query, that why it's actually as simple as that:连接不需要任何子查询,这就是为什么它实际上如此简单:

DB::table('products')
    ->leftJoin('addtionalproducts', 'products.additionalProductId', '=', 'addtionalproducts.product_id')
    ->where('products.product_id', '=', $productId);
    ->get();

https://laravel.com/docs/9.x/queries#joins https://laravel.com/docs/9.x/queries#joins

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM