سؤال

I am using I guess what is referred to a pivot table in Laravel 4 application. I have an users table, a team table and a team_user table (the pivot)

the pivot tables structure is:

id (primary key)
team_id (foreign key to team table)
user_is (foreign key to user table)
created_at
updated_at

In my Team model I want to create a relationship for the teammates.

public function teammates(){
    return $this->belongsToMany('????');
}

How do I show the user's information (first_name, last_name) using the pivot table so I can do something like

@foreach($team->teammates as $teammate)
{{echo $teammate->first_name $teammate->last_name}}
@endforeach
هل كانت مفيدة؟

المحلول

If your keys are default (id) then:

public function teammates(){
    // belongsToMany (RelatedModel, table, thisModelKeyOnPivot, relatedModelKeyOnPivot)
    return $this->belongsToMany('User', 'team_user', 'team_id', 'user_id');
}

نصائح أخرى

This should do the trick:

public function teammates(){
    return $this->belongsToMany('User', 'team_user', 'user_id', 'team_id');
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top