2016-08-02 119 views
0

外鍵我有兩個型號:兩個指向同一個表/模型

  • TRUCK
  • DRIVER

TRUCK有兩個字段其FKS。 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

默認laravel將使用默認的外鍵,

雄辯假設基礎上, 型號名稱#Further reading

所以兩者關係的關係外鍵都指向同一個FK,所以你需要指定如下的外鍵

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

Full code

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'); 
    } 
相關問題