简体   繁体   English

Laravel访问刀片中的外键表列

[英]Laravel access foreign key table column in blade

How can I access a table column using a foreign key in blade so far I have this but it does not work. 到目前为止,我如何使用刀片中的外键访问表列,但是它不起作用。

Inquiry Model / relations 查询模型/关系

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

Client Model 客户模型

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

Device Model 设备型号

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

Controller 调节器

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

View 视图

@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

You cannot access attribute name of stream_id , it's just an integer, what you may try is $inquiryValue->client->name or i think, $inquiryValue->client->first()->name 您无法访问stream_id属性name ,它只是一个整数,您可以尝试使用$inquiryValue->client->name或我认为$inquiryValue->client->first()->name

Be sure to let Laravel know that stream_id is the key used for your relations. 确保让Laravel知道stream_id是用于您的关系的密钥。

You should try with this example like : 您应该尝试使用以下示例:

Updated answer 更新的答案

Controller 调节器

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

View file 查看文件

@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

if you name it stream_id than i think it's better u have a table name streams , if u want to get the client data from inquiry, than u should have client_id column in your inquiry table, same for the device, add device_id column to your inquiry table 如果你的名字的stream_id比我认为这是更好u有一个表名溪流 ,如果u想从查询获得客户端的数据,妳比应该在你的调查CLIENT_ID列,同为设备,DEVICE_ID列到你的询盘加入表

How to access it: @foreach($inquiries as $inquiryKey => $inquiryValue) {{$inquiryValue->client->name}} {{$inquiryValue->device->name}} @endforeach 如何访问它: @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