本文介绍了Laravel HasManyThrough键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个模型:User,Program,UserProgram. UserProgram是其自己的实际模型.

I have 3 models: User, Program, UserProgram. UserProgram is an actual model of its own.

以下是模型在数据库中的外观:

Here are how the models look in the database:

  • 用户
    • id
    • users
      • id
      • id
      • 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?

      推荐答案

      hasManyThrough不用于此目的.您需要many-to-many关系.

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

      class Program {
        public function users() {
          return return $this->belongsToMany('App\User', 'user_programs', 'program_id', 'user_id');
        }
      }
      

      这篇关于Laravel HasManyThrough键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 10:27