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

bellini's avatar

Need help with a query builder scope

I have 3 tables -> scripts -> guidelines -> calls

a script can have multiple guidelines, and a guideline can have multiple calls. in my scripts table I have a active_call column, which is a foreign key corresponding to the current call. I need to build a scope where I filter scripts in which their active call is the first call of their guideline.

so I basically need to compare the active_call ID with the first call from the active call guideline which can be accessed through the guideline_id of the active call. right now I only have this scope in my scripts model:


return $query->whereHas('activeCall', function (Builder $query) {
                //compare this activeCall id with the first call from the activeCall guideline_id
            });

but I have no idea how to proceed with this. any suggestions?

0 likes
2 replies
jlrdw's avatar

I don't know all your data, but try to write a complete query that works without a scope first. Next you should spot the portion that will be the scope part.

Note the example:

    public function scopeOfType($query, $type)
    {
        return $query->where('type', $type);
    }
$users = User::ofType('admin')->get();

This part

$users = User::ofType('admin')->get();    is in the controller
// always the exact same except the parameter, here 'admin' changes.

So the part to dynamically figure and return would be the scope. In example $type.

2 likes
bellini's avatar

Maybe this helps understanding my issue better

This is a scope in my Script model

        return $query->active()
            ->whereHas('activeCall', function (Builder $query) {
                $query->where('closed', 0);
            })->whereHas('calls', function(Builder $query) {
                //here I need to filter only the ones that have calls->first()->id = sctipts.active_call;
            });

Please or to participate in this conversation.