Laravel访问刀片中的外键表列

时间:2017-08-11 07:53:08

标签: php laravel foreign-keys laravel-5.4 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

2 个答案:

答案 0 :(得分:1)

您无法访问name的属性stream_id,它只是一个整数,您可以尝试$inquiryValue->client->name或我认为$inquiryValue->client->first()->name

一定要让Laravel知道stream_id是您关系的关键。

答案 1 :(得分: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