Laravel 6 数据库关系

Laravel 6 database relationships

我不太擅长这门课。

我有两个 table。买家和追踪者。

在跟踪器中 table 我有这些列

id, buyer_id, style_name

买家table是

id, buyer_name

当我检索并显示跟踪器列表时,我希望也能够显示 buyer_name。

在我的 Buyer.php 模型中

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tracker extends Model
{
    /**
     * The attributes that are mass assignable.
     *  
     * @var array
     */
    protected $table = 'trackers';

    protected $fillable = [
        'buyer_id',
        'style_name',
    ];

    public function buyer()
    {
        return $this->hasOne('App\Buyer');
    }
}

我用artisan tinker 来测试。所以,代码是;

$tracker = Tracker::find(1)->buyer;

但是我得到这个错误

Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'buyers.tracker_id' in 'where clause' (SQL: select * from `buyers` where `buyers`.`tracker_id` = 1 and `buyers`.`tracker_id` is not null limit 1)'

它正在买家 table 中寻找 tracker_id,但我只是用它的 ID 检索一个。我做错了什么?

这是trackers的迁移文件

public function up()
{
    Schema::create('pattern_room_trackers', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('buyer_id');
        $table->string('style_name');

        $table->foreign('buyer_id')
        ->references('id')
        ->on('buyers')
        ->onDelete('cascade');
    });
}

我也不知道如何在我的 blade 视图中显示它。

TrackerController.php

 public function index()
 {
   $trackers = Tracker::latest()->paginate(5);
   return view('trackers.index',compact('trackers'))
    ->with('i', (request()->input('page', 1) - 1) * 5);
  }

index.blade.php

      @foreach ($trackers as $tracker)
      <tr>
          <td>{{ ++$i }}</td>
          <td>{{ $tracker->style_name }}</td>
          <td>{{ $tracker->buyer_name }}</td>
      </tr>
       @endforeach

谢谢。

你需要使用 belongsTo 关系。买家是 Tracker 的 parent。

public function buyer()
    {
        return $this->belongsTo('App\Buyer','buyer_id');
    }

并在 blade

<td>{{ $tracker->buyer->buyer_name }}</td>

阅读 laravel 文档 here 关于一对多反向关系的内容。