Home > database >  Laravel Query/ Relational database query
Laravel Query/ Relational database query

Time:11-17

I have two data tables vehicles and trips, which have a one to many relationship and allow for multiple trips per vehicle. route is a column in the trips table. I want to see the vehicle list for a specific route, so I ran the following query.

$trips = Trip::with('vehicle')
     ->where('route', $route)
     ->get()->pluck('vehicle');

It work's fine, returns a vehicle collection. Now that I have the vehicle collection I want the active trip information with every vehicle model. I tried the following query.

$trips = Trip::with('vehicle', ['vehicle.activeTrip' => function ($query) {
            $query->where('status', 0);
        }])
        ->where('route', $route)
        ->get()->pluck('vehicle');

status = 0 indicates an active trip. But it is unsuccessful anyway. I got an error with the message Method name must be a string. Can anyone assist me in resolving my problem?

CodePudding user response:

Would you use this syntax


$trips = Trip::with(['vehicle','vehicle.activeTrip' => function ($query) {
            $query->where('status', 0);
        }])
        ->where('route', $route)
        ->get()->pluck('vehicle');

CodePudding user response:

I just came across another solution. To retrieve the active trip data, we could use the Laravel ofMany method inside the Trip model.

public function activeTrip(){
return $this->hasOne(Trip::class, 'vid')->ofMany([], function ($query) {
    $query->where('status', 0);
});}
  • Related