繁体   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