问题
I have 3 models: User, Program, UserProgram. UserProgram is an actual model of its own.
Here are how the models look in the database:
- users
- id
- programs
- id
- user_programs
- user_id
- program_id
I would like to have in my Program model:
function users() {
return $this->hasManyThrough('App\User','App\UserProgram');
}
But this does not work. How can I make this relationship work?
回答1:
hasManyThrough
is not used for this purpose. You need a many-to-many
relationship.
class Users {
public function programs() {
return $this->belongsToMany('App\Program', 'user_programs', 'user_id', 'program_id');
}
}
and
class Program {
public function users() {
return return $this->belongsToMany('App\User', 'user_programs', 'program_id', 'user_id');
}
}
来源:https://stackoverflow.com/questions/38287685/laravel-hasmanythrough-keys