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

ccarstens's avatar

Compare columns of model and it's related model through whereHas

Hi,

I have three models that are related to each other:

  1. Vehicle (id, driver_id)
  2. Allocation (allocated vehicle with booking data) (departure_date, vehicle_id, driver_id)
  3. Driver (id, name)

I want to query all Allocations, where the 'driver_id' is the same as in the related vehicle. In my logic I would have to do the following:

// in Allocation
...
$query->whereHas('vehicle', function($driverQuery){
        $driverQuery->where('driver_id', '<>', DRIVER_ID_OF_ALLOCATION);
});

How can I get the actual value of driver_id of the queried allocation to be in the where clause? Is that even possible?

Thank you a lot for helping me! <3 Cornelius

0 likes
4 replies
Snapey's avatar

There is use() for passing data into closures

...
$query->whereHas('vehicle', function($driverQuery) use ($driver){
        $driverQuery->where('driver_id', '<>', $driver);
});
ccarstens's avatar

Thank you snapey for your reply!

I try to achieve that in a scope (would have been smart to share that detail).

//Allocation.php
...

public function scopeWithMatchingDrivers($query)
{
    return $query->whereHas('vehicle', function($driverQuery){
            $driverQuery->where('driver_id', '<>', DRIVER_ID_OF_ALLOCATION);
    });
}

Passing a value into the closure would be great but there is not the single $driver Object I want to test against, but I want to compare the driver_id of each Allocation with the driver_id of the related vehicle.

Of course I could retrieve data and then loop through it but I would be nice to solve this just by using the query builder.

I hope I was able to clarify better what I pursue.

Thank you, Cornelius

staudenmeir's avatar

Try whereColumn():

$driverQuery->whereColumn('driver_id', '<>', 'allocations.driver_id');

Shouldn't the operator be = instead of <>?

Snapey's avatar

if its to find vehicles that are not allocated to the driver, there is a doesntHave function

Please or to participate in this conversation.