Laravel blade one-to-one @foreach 循环中的关系

Laravel blade one-to-one relationship in @foreach loop

我在 Laravel 中显示一对一关系时遇到问题。

我在数据库中有 tables: manufacturers 默认 Laravel id 列和 cashregisters with manufacturer_id column releated to id from manufacturers table.

我在模型中这样做:

收银台

class Cashregister extends Model
{
    protected $table = "cashregisters";

    public function manufacturer(){

        return $this->hasOne('App\Manufacturer','id');

    }
}

制造商

class Manufacturer extends Model
{
    protected $table = "manufacturers";

    public function cashregisters(){

        return $this->belongsTo('App\Cashregister');

    }
}

我觉得还行。接下来我在 CashregisterController 中做 index():

$cashregisters = Cashregister::all();
return view('cashregisters.index')->withCashregisters($cashregisters);

在收银机索引视图中,我执行该循环:

    <tbody>
    @foreach ($cashregisters as $cashregister)
    <tr>
    <th>{{ $cashregister->id }}</th>
    <td>{{ $cashregister->manufacturer_id }}</td>
                         ......
    <td>{{ $cashregister->DataNastPrzegUrzFisk }}</td>
    @endforeach
    </tr>
    </tbody>

而且效果很好。显示 收银机 table 中的所有内容。

我想显示制造商名称而不是 manufacturer_id,所以我尝试这样做:

 <td>{{ $cashregister->manufacturer->name }}</td>

但是我遇到了一个错误。

接下来我在互联网上搜索并尝试做那件事

@foreach ($cashregisters as $cashregister)
        <tr>
        <th>{{ $cashregister->id }}</th>
      @foreach ($cashregister->manufacturer() as $item)
        <td>{{ $item->name}}</td>
      @endforeach
                             ......
        <td>{{ $cashregister->DataNastPrzegUrzFisk }}</td>
        @endforeach
        </tr>
        </tbody>

但是这段代码什么也没显示 :( 谁能帮我解决这个问题。毕竟当我 table 执行该代码时:

<td>{{ $cashregister->manufacturer->name}}</td>

显示了一些信息,所以我觉得关系还可以。

使用with()加载关系:

$cashregisters = Cashregister::with('manufacturer')->all();

然后这将显示制造商:

$cashregister->manufacturer->name

您需要为制造商设置本地密钥,如下所示:

    class Cashregister extends Model
{
    protected $table = "cashregisters";

    public function manufacturer(){

        return $this->hasOne('App\Manufacturer','id', 'manufacturer_id');

    }
}