簡體   English   中英

在Laravel和Eloquent中獲取2個以上聯接表的數據

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

這是我的桌子。

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

現在我想在表格中顯示結果數據

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

想象一下,如果它是AJAX,並且在將數據發送到視圖之前必須連接表。 我已經在模型中定義了關系。 但是使用with()方法,我只能同時調用2個em,但我不知道如何在視圖中調用它們。

無論如何,有沒有不使用普通的DB::class而只是雄辯地使用了?

您是否嘗試過:

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

您應該能夠在控制器中執行類似的操作,以在視圖中獲得該結果。

$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