簡體   English   中英

Laravel查詢獲取相關數據

[英]Laravel query getting related data

我有一個查詢(如下),在編輯頁面中可以找到產品規格列表,到目前為止,它可以返回我的數據。 問題是我無法獲得父母的信息。

Query

$specs = DB::table('product_subspecification')
->where('product_id', '=', $product->id)
->join('subspecifications', 'subspecifications.id', '=', 'product_subspecification.subspecification_id')
->get();

Result

{#3106 ▼
  +"id": 8
  +"product_id": 15
  +"subspecification_id": 8
  +"title": "Xplorer 5500M"
  +"specification_id": 6
  +"status_id": 1
  +"created_at": "2018-08-06 12:42:40"
  +"updated_at": "2018-08-06 12:42:40"
}

問題

問題是Xplorer 5500M實際上是我的子規格(我將其保存為產品規格,並且在這種情況下it has parentKeyboard我也需要返回該父項(鍵盤)名稱。

因此,稍后在刀片中我將看到以下內容:

+------------+---------------+
|   Parent   | Specification |
+------------+---------------+
|  Keyboard  | Xplorer 5500M |
+------------+---------------+

Blade

@foreach($specs as $spacsdf)
  <tr>
    <td>Parent name here</td>
    <td>{{$spacsdf->title}}</td>
    <td>Del Button</td>
  </tr>
@endforeach

PS:我曾嘗試加入規格表(即父母表名),但是這次我只得到了Keyboard而不是Xplorer 5500M

這是我嘗試過的第二個查詢:

$specs = DB::table('product_subspecification')
 ->where('product_id', '=', $product->id)
 ->join('subspecifications', 'subspecifications.id', '=', 'product_subspecification.subspecification_id')
 ->join('specifications', 'specifications.id', '=', 'subspecifications.specification_id')
 ->get();

任何想法?

如果不指定要為聯合查詢檢索的字段,則如果您具有同名的列,則可能會遇到一些不必要的行為。

我建議嘗試使用“選擇”方法指定所需的字段:

$specs = DB::table('product_subspecification')
 ->select('product_subspecification.id', 'specifications.title as parent', 'subspecifications.title as subspec')
 ->where('product_id', '=', $product->id)
 ->join('subspecifications', 'subspecifications.id', '=', 'product_subspecification.subspecification_id')
 ->join('specifications', 'specifications.id', '=', 'subspecifications.specification_id')
 ->get();

然后,您可能會得到如下結果:

{#3106 ▼
  +"id": 8
  +"subspec": "Xplorer 5500M"
  +"parent": "Keyboard"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM