Laravel HasManyThrough Keys

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

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');   } } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!