Ad

Using Relationships In Laravel Eloquent With Bridge Table

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

Answer

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

Ad
source: stackoverflow.com
Ad