Laravel 查询结果子数组没有 eloquent

Laravel Query to result with sub array no eloquent

请帮助我完成我在学校的项目。我如何在 laravel 控制器中查询类似这种情况。 我有三个 table: Shipping_table 和 Shipping_products 和 tbl_products,现在我的 table 结构是这样的:

运费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)

现在我想要的是这样的查询结果: 我想在运输 table 中获取所有内容,在子数组中我想获取在 shipping_products 中列出的具有所需运输 ID 的产品。

结果如下:示例我有 2 Shipping_table 个值

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"
 }
}

SQL 部分很简单(使用 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

php 部分更复杂,因为您必须在循环中获取结果并检测 Ship_idProduct_id 中的变化并将结果数组放入。

因为这是家庭作业..我会把它留作练习...


这是一个快速算法示例 - 未经测试但逻辑合理。

$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
}