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

edalzell's avatar

Query scopes or new model for self-reference?

I have a User that has a trainer_id, that is the id of another user.

I'd like to be able to get all the Trainers. Does one normally create a Trainer model that uses the users table and make some query methods (all, etc) that return the correct data?

Or do I make some query scopes or something on the User model (isTrainer, or whatever)?

Thanks in advance for your help.

0 likes
1 reply
click's avatar
click
Best Answer
Level 35

There is no need for another model. But it depends (as always). Assuming that you have your relationships setup. belongsTo: trainer() and hasMany: trainees()

You can use this: https://laravel.com/docs/6.x/eloquent-relationships#querying-relationship-existence

So you could do:

$trainers = \App\User::has('trainees')->get(); 

update: and for readability you could wrap it in a scope so you can do:

public function scopeTrainers($query) {
    $query->has('trainees');
}

$trainers = \App\User::trainers()->get(); 
1 like

Please or to participate in this conversation.