'Difficulty properly joining tables in Laravel query
I'm having difficulty properly joining tables in L9. This joins my products and additionalProducts tables. The mission is to get all the products that can be added with productId(x). I have the Product table with all the info and additonalProduct that look like this:
| id | product_id | additionalProductId |
|---|---|---|
| 1 | 1 | 2 |
| 2 | 1 | 4 |
| 3 | 2 | 3 |
| 4 | 2 | 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.
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 = $productsInfo[0]->product_id;
(when i print it with dd it show id=1 or 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();
Solution 1:[1]
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:
->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.
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();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
