2015-11-14 36 views
0

這裏是我的表格。獲取Laravel中超過2個連接表的數據和雄辯

╔════════════╤═╤══════════╤═╤═══════╗ 
║ 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,但我不知道如何在視圖中調用它們。

是否有反正不使用普通DB::class只是用口才?

+0

您是否建立了關係? – Andrius

+0

@Andrius是的,我有。 –

+0

好的。問題是如何用保險解析Device對象(我懷疑是一對一關係)還是品牌(又是一對一)?很明顯,你需要在控制器或模型中進行解析,而不是像前面提到的那樣進行解析。 – Andrius

回答

0

你應該能夠做到在控制器中這樣的事情來得到這一結果在您的視圖。

$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 

]);

+0

這就像一個魅力。謝謝你教我,我可以像那樣使用它。 –

+0

只有一個修改,我必須使用鏈仍然。例如,代替'$ insurance-> brand-> name',我應該寫'$ insurance-> device-> brand-> name',但是仍然感謝你。 –

+0

@ArmanMomeni哦,當然!我確定了我的答案 –

0

你有沒有tryed這樣:

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 
+0

@ArmanMomeni我編輯了答案 – genespos

+0

謝謝你的工作。 –