簡體   English   中英

Laravel訪問刀片中的外鍵表列

[英]Laravel access foreign key table column in blade

到目前為止,我如何使用刀片中的外鍵訪問表列,但是它不起作用。

查詢模型/關系

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

您無法訪問stream_id屬性name ,它只是一個整數,您可以嘗試使用$inquiryValue->client->name或我認為$inquiryValue->client->first()->name

確保讓Laravel知道stream_id是用於您的關系的密鑰。

您應該嘗試使用以下示例:

更新的答案

調節器

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM