2017-08-11 18 views
0

如何使用刀片中的外鍵訪問表列中的內容到目前爲止,我擁有此功能,但無法使用。Laravel訪問刀片中的外鍵表列

詢價型號/關係

public function client() 
{ 
    return $this->belongsTo(Client::class); 
} 
public function device() 
{ 
    return $this->belongsTo(Device::class); 
} 

客戶端模型

public function inquiry() 
{ 
    return $this->hasMany(Inquiry::class); 
} 
public function devices() 
{ 
    return $this->hasMany(Device::class); 
} 

設備型號

public function inquiry() 
{ 
    return $this->hasMany(Inquiry::class); 
} 

控制器

public function index() 
{ 
    $inquiries = Inquiry::all(); 
    return view('stream.index', compact('inquiries')); 
} 

查看

@foreach($inquiries as $inquiryKey => $inquiryValue) 
    <tr> 
     // stream id is the foreign that table has a column with names ... 
     <th scope="row">{{ $inquiryValue->stream_id }}</th>  // works 
     <th scope="row">{{ $inquiryValue->stream_id->name }}</th> // does not work -> trying to get property of none object 
+1

的stream_id是表中的字段? –

+0

你只是通過foreach像$查詢 - >客戶端然後你可以使用客戶端表數據 –

+0

@AddWebSolutionPvtLtd你能給我一個示例代碼請 – junikear

回答

1

您不能訪問屬性namestream_id,它只是一個整數,你可以嘗試爲$inquiryValue->client->name或我認爲,$inquiryValue->client->first()->name

一定要讓Laravel知道stream_id是使用的密鑰爲你的關係。

+0

我認爲這工作'$ inquiryValue-> client- > name'我會進一步檢查並可能稍後接受你的回答 – junikear

+0

Inquiry :: all中的每個對象都是一個Inquiry模型,因此讓你使用'client'和'device'關係,因此,執行'$ inquiryValue-> client'返回與之相關的客戶端,您現在可以訪問其名稱。您還應該讓Laravel知道您在關係中使用stream_id作爲您的foreign_key。 – Wreigh

0

你應該用這個例子類似嘗試:

更新答案

控制器

public function index() 
{ 
    $inquiries = Inquiry::all(); 
    return view('stream.index', compact('inquiries')); 
} 

查看文件

@foreach($inquiries as $inquiryKey => $inquiryValue) 
    <tr> 
     // stream id is the foreign that table has a column with names ... 
     <th scope="row">{{ $inquiryValue->client->name }}</th>  // works 
    </tr 
@endforeach 
+0

沒有工作,因此我不明白'Inquiry :: with('client') - > get();'返回與Inquiry :: all();'一樣的錯誤:'property [client]不存在這個集合實例' – junikear

+0

@junikear請給我名稱字段的表名稱 –

+0

表名稱是客戶端,詢問,設備 – junikear

0

,如果你的名字的stream_id比我認爲這是更好u有一個表名,如果u想從查詢獲得客戶端的數據,妳比應該有查詢表CLIENT_ID列,同爲設備添加DEVICE_ID列到你的查詢

如何訪問: @foreach($inquiries as $inquiryKey => $inquiryValue) {{$inquiryValue->client->name}} {{$inquiryValue->device->name}} @endforeach