简体   繁体   English

在Laravel和Eloquent中获取2个以上联接表的数据

[英]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. 想象一下,如果它是AJAX,并且在将数据发送到视图之前必须连接表。 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. 但是使用with()方法,我只能同时调用2个em,但我不知道如何在视图中调用它们。

Are there anyways to not use plain DB::class and just use eloquent? 无论如何,有没有不使用普通的DB::class而只是雄辩地使用了?

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

]); ]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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