Ad
Laravel - Get Additional Attributes Of Many To Many Table
I got the following tables
- actors
- id
- name
- stats
- id
- name
- actor_stat
- actor_id
- stat_id
- quantity
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?
Ad
Answer
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;
Ad
source: stackoverflow.com
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms
Ad