简体   繁体   中英

Getting data of more than 2 joined tables in Laravel and Eloquent

Here are my tables.

╔════════════╤═╤══════════╤═╤═══════╗
║ Insurances │ │ Devices  │ │ Brands║
╠════════════╪═╪══════════╪═╪═══════╣
║ id         │ │ id       │ │ id    ║
╟────────────┼─┼──────────┼─┼───────╢
║ IMEI       │ │ type     │ │ name  ║
╟────────────┼─┼──────────┼─┼───────╢
║ device_id  │ │ name     │ │       ║
╟────────────┼─┼──────────┼─┼───────╢
║ user_id    │ │ brand_id │ │       ║
╚════════════╧═╧══════════╧═╧═══════╝

now I wanna show the results data in a table like

╔══════╤════════════╤═════════════╤══════════════╤═════════╗
║ IMEI │ brand_name │ device_name │ device_price │ user_id ║
╚══════╧════════════╧═════════════╧══════════════╧═════════╝

Imagine if it is AJAX and I have to join the tables before sending the data to the view. I have defined the relationships in models. but with the with() method I only can call 2 of em the same time and yet I dunno how to call them in the view.

Are there anyways to not use plain DB::class and just use eloquent?

Have you tryed so:

SELECT IMEI, B.name AS Brand_Name, D.name AS Device_Name, D.price, user_id
FROM Insurances I
INNER JOIN Devices D ON I.device_id = D.id
INNER JOIN Brands B on D.brand_id = B.id

You should be able to do something like this in your controller to get that result in your view.

$insurance = Insurance::with('device.brand')->find($id);

return json_encode([
  'imei' => $insurance->IMEI,
  'brand_name' => $insurance->device~>brand->name,
  'device_name' => $insurance->device->name,
  'device_price' => $insurance->device->price
  'user_id' => $insurance->user_id

]);

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