skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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);
    });}
    

  2. Would you use this syntax

    
    $trips = Trip::with(['vehicle','vehicle.activeTrip' => function ($query) {
                $query->where('status', 0);
            }])
            ->where('route', $route)
            ->get()->pluck('vehicle');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search