please help me in my project at school. How can i query in laravel controller something like this situation. I have three tables: Shipping_table and Shipping_products and tbl_products, now my table structure is this:
Shipping table:
Ship_ID (INT AUTO INC)
AMOUNT (DOUBLE,2)
NAME (VARCHAR)
SHIP_DATE (DATE)
RECEIVER (VARCHAR)
Shipping_products:
ID (INT AUTO INC)
Ship_id (foreign key from shipping table)
Product_id
Products_table:
Product_id (Auto Inc)
name(varchar)
Qty(int)
Description (varchar)
now what i want is having a query result like this: I want to get all in the shipping table and in sub-array i want to get the products that is being listed in shipping_products with the desired shipping id.
Something a result like this: EXAMPLE I HAVE 2 Shipping_table values
Array(2) {
[0] Array(4) {
['Ship_id'] "1"
['Amount'] "10000"
['Ship_date'] "1995-12-11"
['Ship_products'] Array(3)
['id'] "1" Array(2)
['product_id'] "5"
['name'] "Product 1"
['id'] "2" Array(2)
['product_id'] "6"
['name'] "Product 2"
['id'] "3" Array(2)
['product_id'] "10"
['name'] "Product 15"
}
[1] Array(4) {
['Ship_id'] "2"
['Amount'] "15000"
['Ship_date'] "1995-12-15"
['Ship_products'] Array(2)
['id'] "1" Array(2)
['product_id'] "5"
['name'] "Product 1"
['id'] "2" Array(2)
['product_id'] "6"
['name'] "Product 2"
}
}
The SQL part is easy (using JOINS
)
SELECT *
FROM Shipping S
LEFT JOIN Shipping_Products SP
ON SP.Ship_Id=S.Ship_Id
LEFT JOIN Products P
ON P.Product_id=SP.Product_id
The php
part is more complicated, as you have to get the results in a loop and detect changes in Ship_id
and Product_id
and put in the resulting array.
Since this is homework .. I'll leave it as an exercise ...
THIS IS A QUICK ALGORITHM EXAMPLE - untested but logically sound.
$cur_ship = '';
$cur_prod = '';
$results = array();
foreach ($resultset as $key => $row) {
if ($cur_ship != $row['Ship_id']) {
$cur_ship = $row['Ship_id'];
$cur_prod = '';
$results[$cur_ship] = array();
// Fill ship info from $row
}
if ($cur_prod != $row['Product_id']) {
$cur_prod = $row['Product_id'];
$results[$cur_ship][$cur_prod] = array();
// Fill Product info from $row
}
// FILL OUR $results[$cur_ship][$cur_prod] from $row
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.