join - Relationships in has many laravel -
i have 3 tables units
, renters
, renter_units
. fields of render_units
table id
, unit_id
, renter_id
.
my render
model is
public function renter_unit() { return $this->hasmany('app\renterunit'); }
and in renterscontroller
$renters = renter::with('renter_unit')->get();
so $renders
array shows
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 } ] }
but want relationship
array renter_unit
field too. how achieve ?
may should use many-to-many relationship. if so, don't need pivot class renterunit
, renter_unit
table
code below
public function units() { return $this->belongstomany('app\unit'); }
unit.php public function renters() { return $this->belongstomany('app\renter'); }
in renterscontroller can access units related each renter instance
$renters = renter::with('units')->get(); foreach($renters $renter) { $units = $renter->units; //here are, it's collection }
Comments
Post a Comment