Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

LiamA's avatar
Level 1

Pivot table for two classes that extend the User class

Pivot table for two classes that extend the User class

Hi, I'm new to Laravel and I'm trying to figure out how to properly use a pivot table. I have two models that extend the User model: Teacher and Student. They both use the 'users' table in database.

class Teacher extends User { public function students(){ return $this->belongsToMany(Student::class); } }

class Student extends User { }

There is also a pivot table named 'student_teacher' with the relationships between students and teachers. When I create model instances and use attach() to attach instances of the other model, the pivot table is populated with their ids (teacher_id and student_id).

My problem is that when I try to make a query with some relational coniditions, such as:

students: Student::has('teachers') )

I get the following SQL error:

Column not found: 1054 Unknown column 'laravel_reserved_1.teacher_id' in 'where clause' (SQL: select * from users where exists (select * from users as laravel_reserved_1 where users.id = laravel_reserved_1.teacher_id) and type = teacher)'

So I understand that Laravel is searching for the 'teacher_id' column in the users table instead of in the pivot table where that data is stored. How do I fix this?

0 likes
1 reply
Spiral's avatar
/*Model*/
class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}

/*controller*/
$user = App\User::find(1);

foreach ($user->roles as $role) {
    echo $role->pivot->created_at;
}
/*Model*/
class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}

/*controller*/
$user = App\User::find(1);

foreach ($user->roles as $role) {
    //
}

$roles = App\User::find(1)->roles()->orderBy('name')->get();

Migration

2020_02_20_182537_create_userss_table.php
2020_02_20_182537_create_roles_table.php
2020_02_20_182537_create_role_users_table.php

Please or to participate in this conversation.