2016-06-11 116 views
0

我有三個表units,renters,renter_unitsrender_units的字段爲idunit_idrenter_id關係中有很多laravel

Render模型

public function renter_unit() 
    { 
     return $this->hasMany('App\RenterUnit'); 
    } 

在我RentersController

$renters = Renter::with('renter_unit')->get(); 

所以$renders陣列顯示

Collection {#212 ▼ 
    #items: array:1 [▼ 
    0 => Renter {#206 ▼ 
     #fillable: array:3 [▶] 
     #table: "renters" 
     #guarded: array:1 [▶] 
     #connection: null 
     #primaryKey: "id" 
     #perPage: 15 
     +incrementing: true 
     +timestamps: true 
     #attributes: array:7 [▶] 
     #original: array:7 [▶] 
     #relations: array:1 [▼ 
     "renter_unit" => Collection {#210 ▼ 
      #items: array:2 [▼ 
      0 => RenterUnit {#213 ▼ 
       #fillable: array:2 [▶] 
       #table: "renter_units" 
       #guarded: array:1 [▶] 
       #connection: null 
       #primaryKey: "id" 
       #perPage: 15 
       +incrementing: true 
       +timestamps: true 
       #attributes: array:5 [▼ 
       "id" => 1 
       "unit_id" => 1 
       "renter_id" => 1 
       "created_at" => "2016-06-11 02:40:44" 
       "updated_at" => "2016-06-11 02:40:44" 
       ] 
       #original: array:5 [▶] 
       #relations: [] 
       #hidden: [] 
       #visible: [] 
       #appends: [] 
       #dates: [] 
       #dateFormat: null 
       #casts: [] 
       #touches: [] 
       #observables: [] 
       #with: [] 
       #morphClass: null 
       +exists: true 
       +wasRecentlyCreated: false 
      } 
      1 => RenterUnit {#214 ▶} 
      ] 
     } 
     ] 
     #hidden: [] 
     #visible: [] 
     #appends: [] 
     #dates: [] 
     #dateFormat: null 
     #casts: [] 
     #touches: [] 
     #observables: [] 
     #with: [] 
     #morphClass: null 
     +exists: true 
     +wasRecentlyCreated: false 
    } 
    ] 
} 

但我想relationship陣列renter_unit場了。如何實現這一目標?

回答

0

可能是你應該使用Many-To-Many的關係。如果是這樣,那麼你不需要任何支點類像RenterUnit,只有renter_unit
那麼你的代碼就會像下面

Renter.php
public function units() 
{ 
    return $this->belongsToMany('App\Unit'); 
} 
Unit.php
public function renters() 
{ 
    return $this->belongsToMany('App\Renter'); 
} 

在你RentersController您可以訪問與每個租用實例相關的單位

$renters = Renter::with('units')->get(); 
foreach($renters as $renter) { 
    $units = $renter->units; //here they are, it's a collection 
}