如何使用联接从3级表中获取数据[Laravel]

时间:2019-03-13 06:40:18

标签: php mysql database laravel join

我想使用 bd_products

的主键(ID)获取存储在 bd_product_item_ledgers 中的产品数量

bd_products 已链接到 bd_product_ledgers 然后, bd_product_ledgers 链接到 bd_product_item_ledgers

表:bd_products

---------------------------------------------------------------------------------
| id |  name  |    description   | image     | created_at | updated_at
---------------------------------------------------------------------------------
| 1  | shoe   | this is a shoe   | 15243.jpg | 
---------------------------------------------------------------------------------

表:bd_product_ledgers

---------------------------------------------------------------------------------
| id |  product_id  |  cost    | created_at | updated_at
---------------------------------------------------------------------------------
| 1  |      1       | 500.00   |
---------------------------------------------------------------------------------

表:bd_product_item_ledgers

---------------------------------------------------------------------------------
| id |  product_ledger_id |  quantity  | created_at | updated_at
---------------------------------------------------------------------------------
| 1  |          1         |   200      |
---------------------------------------------------------------------------------

我可以得到产品的成本,因为那里有ID,但是我怎么也可以得到数量?

简单的MySQL查询或Laravel雄辩的话,一切都会很好。

谢谢!

2 个答案:

答案 0 :(得分:1)

创建三个模型产品,项目,分类帐,并在产品模型和分类帐模型中定义您的关系分类帐,这样您就可以通过类似的查询获取数据,

$data = Product::with('ledgers.item')->get();

答案 1 :(得分:1)

我不确定,但是我创建了带有以下表格的演示项目并输入了您提供的数据

  

其PURLY数据库外观版本

[如果您需要使用ELOQUENT方式,请分享  您的型号名称]

public function index()
    { 
        $selctArray = [
                'bd_products.name',
                'bd_products.description',
                'PRDLED.cost as productCost',
                'PRDITLED.quantity as productQuantity',

        ];

        $joinQuery = DB::table('bd_products')
                        ->leftJoin('bd_product_ledgers as PRDLED','PRDLED.product_id','=','bd_products.id')
                        ->leftJoin('bd_product_item_ledgers as PRDITLED','PRDITLED.product_ledger_id','=','PRDLED.id')
                        ->select($selctArray)->get();
dd($joinQuery);

        }

QUERY IMAGE 如果它不能满足您的要求,请在下面评论,并改善您的问题