两个外键指向同一个表/模型

时间:2016-08-02 02:23:13

标签: laravel model-view-controller laravel-5 model eloquent

我有两种模式:

  • 卡车
  • DRIVER

TRUCK有两个FK字段。 Driver (FK)Driver2 (FK)

当我尝试使用驱动程序和驱动程序2的卡车时,我得到两个相同的记录。

    $truck = $this->instance->truck()->where('id', $id)
            ->with(['driver', 'driver2',])
            ->firstOrFail();

我的卡车型号:

class Truck extends Model
{
    use SoftDeletes;       
    protected $table = 'trucks';
    protected $guarded = ['id'];
    protected $dates = ['deleted_at'];

    public function driver()
    {
        return $this->hasOne('App\Models\Driver');
    }

    public function driver2()
    {
        return $this->hasOne('App\Models\Driver');
    }   

我的司机型号:

class Driver extends Model
{
    use SoftDeletes;    
    protected  $table = 'drivers';
    protected $guarded = ['id'];
    protected $dates = ['deleted_at'];

    public function truck()
    {
        return $this->belongsTo('App\Models\Truck');
    }

我仍然是laravel的新手,而且我遇到了困难。我应该创建另一个模型吗?

1 个答案:

答案 0 :(得分:1)

默认情况下,laravel将使用默认外键

  

Eloquent假设关系的外键基于   型号名称#Further reading

因此两个关系都指向相同的 FK ,所以你需要指定外键如下

   return $this->hasOne('App\Models\Driver', 'Driver');
   return $this->hasOne('App\Models\Driver', 'Driver2');

完整代码

class Truck extends Model
{
    use SoftDeletes;       
    protected $table = 'trucks';
    protected $guarded = ['id'];
    protected $dates = ['deleted_at'];

    public function driver()
    {
        return $this->hasOne('App\Models\Driver', 'Driver');
    }

    public function driver2()
    {
        return $this->hasOne('App\Models\Driver', 'Driver2');
    }