How to set up a belongsTo relationship properly?

Posted 5 months ago by MartinZeltin

I have 2 tables "users" and "employees". I have set up a relationship for users and employees but can't figure out how to do it the other way around.

users

| id | username | password |
| 1  |  Martin  | c98d09dx |
| 2  |   John   | b23d09ee |

employes

| id | user_id |     fullname     |
| 1  |    1    |   Martin Zeltin  |
| 2  |    2    |     John Doe     |

My Users Model looks like this. I am able to get $user->employee->fullname for example

class Users
{
    public function employee()
    {
        return $this->hasOne('App\Models\Employees', 'user_id');
    }
}

But how can I do it the opposite direction since there is no employee_id on the Users table.

I know that with a simple SQL query it would be like this

SELECT * FROM users WHERE employee_id = ?

I tried this in my Employees Model but it did not work.

class Employees extends Model
{
    public function user()
    {
        return $this->belongsTo('App\Models\Users');
    }
}

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.