2016-06-11 8 views
0

У меня есть три стола units, renters, renter_units. Поля render_units стол id, unit_id, renter_id.Отношения во многих ларавеле

Моя 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 
} 
Смежные вопросы