简体   繁体   中英

Laravel query getting related data

I have a query (below) where i get product specifications list in edit page, so far it's working to return my data. The problem is i cannot get their parents info.

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

Issue

The issue is Xplorer 5500M is actually my sub-specification (which I saved it as my product specification and it has parent in this case is Keyboard I need to return that parent (Keyboard) name as well.

So later in my blade I will have something like:

+------------+---------------+
|   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: I've tried to join specifications table (is parents table name) but all I got was Keyboard this time instead of Xplorer 5500M .

This was the second query I've tried:

$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();

Any idea?

If you do not specify which fields you would like to retrieve for a joined query, you might get some unwanted behaviour if you have equally named columns.

I would suggest trying to specify the fields you need with the "select" method:

$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();

Then you could possibly get a result like:

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM