4

I have an app that handles user info, and one of the pieces of data we collect is what school(s) they're attending. We have a User object, School object, and a UserSchool object.

This is the user_schools table:

user_id (int),school_id (int)

With the following records for instance:

100, 20
200, 500
200, 10
300, 10

I'm trying to get all schools for the current user (say user 200). This is my UserSchool object:

class UserSchool extends Model
{
    var $table = 'user_schools';

    function user() {
        return $this->belongsTo('User');
    }

    function school() {
        return$this->belongsTo('School');
    }

}

In User I have the following relations defined:

public function schools()
    {
        return $this->hasManyThrough('School', 'UserSchool');
    }

    public function userSchools()
    {
        return $this->hasMany('UserSchool');
    }

When I var_dump($user->schools) I get no results, even though I know it should be returning multiple Schools. What am I doing wrong? I'm sure this must have been asked before but I don't know what the actual term for this intermediate type of relationship is (bridge table? pivot table?).

Edit: Either way, most of the examples I've looked at haven't worked. I've also tried:

public function schools()
    {
        return $this->hasManyThrough('School', 'UserSchool',  'school_id');
    }
Thomas Kim
  • 15,326
  • 2
  • 52
  • 42
StackOverflowed
  • 5,854
  • 9
  • 55
  • 119

1 Answers1

5

In fact you don't need to have UserSchool object here for this relationship

For User model you can use create the following relationship:

public function schools() 
{
   return $this->belongsToMany(School::class, 'user_schools');
}

And now you can get schools of user using something like this:

$user = User::find(1);
foreach ($user->schools as $school) 
{
   echo $school->name;
}

This is standard many to many relationship

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • Worked fine, however for PHP 5.4 had to change School::class to "School". Thank you. I would have thought a hasManyThrough relationship would have been required, so thanks for pointing me in the right way. – StackOverflowed Jan 03 '16 at 22:37