Reputation: 193
I got three tables routines, measurements and pools, their pivot table is measure_routine which also stores a pool_id which references a pool in the pools table. The setup looks like such:
routines:
id
value
date
time
emp_id (To reference which employee conducted the task)
measurements:
id
title
pools
id
name
and the pivot table, measure_routine:
routine_id
measure_id
pool_id
Thus far I have defined in my models:
Routine.php
class Routine extends Eloquent
{
public function measurements
{
return $this->belongsToMany('Measurement', 'measure_routine', 'routine_id', 'measure_id', 'pool_id')->withPivot('pool_id');
}
}
Measurement.php
class Measurement extends Eloquent
{
public function routines()
{
return $this->belongsToMany('Routine', 'measure_routine')->withPivot('pool_id');
}
}
Pool.php
class Pool extends Eloquent
{
public function measurement_routine()
{
return $this->hasMany('measure_routine', 'pool_id');
}
}
What I was wondering is how I would go about extracting the pool_id (or possibly the pool name from the pool table) using eloquent?
Currently I've tried using $data = Routine::has('measurements')->get() in the controller, and then trying {{ $data->pivot->pool_id }} in the view, but that resulted in a trying to get property of non-object error.
Upvotes: 1
Views: 338
Reputation: 146239
You may try something like this (To get the first item from collection and pivot):
$data = Routine::has('measurements')->get();
$data->first()->measurements->first()->pivot->pool_id;
Because, $data
is a collection of Routine
returned by get()
so the first item has another collection of measurements
, so again to get the first measurements
from the collection you may use first()
again and then access the pivot->pool_id
, so you may also use a loop in your view
as well, something like this:
@foreach($data as $routine)
{{ $routine->property }}
@foreach($routine->measurements as $measurement)
{{ $measurement->property }}
{{ $measurement->pivot->property }}
@endforeach
@endforeach
Upvotes: 1