I got the following tables
I want, given an actor's name, take all the quantities associated.
Actor model:
class Actor extends Model
{
public function stats()
{
return $this->belongsToMany('App\Stat', 'actor_stat')->withPivot('quantity');
}
}
Stat model:
class Stat extends Model
{
public function users()
{
return $this->belongsToMany('App\User', 'actor_stat')->withPivot('quantity');
}
}
Query
public function request(){
$actors = Actor::where('name','Jack')->first();
$stat = $actors->pivot->quantity; //??
return response()->json(['actors' => $actors, 'stat' => $stat]);
}
Suggestions?
you can use eager loading to load related table like this:
$actors = Actor::with('stats')->where('name','Jack')->first();
//do loop foreach actor state then you can access to quantity column
foreach($actors->states as $state)
$state->pivot->quantity;