0

I have a One To Many (Inverse) relation on my laravel 5.4 application. There are two models Sale and Vehicle which are related and associated with the scene.

The relation on the Sale model is :

public function vehicle()
    {
        return $this->belongsTo('App\Models\Vehicle','vehicle_id');
    }

Table sales has following fields : id, vehicle_id, date_time, status etc.

Table vehicles has following fields : id, reg_number, volume, status etc.

What I want is, sum of the field 'vehicles.volume' of Sale records within the search conditions.

I have tried some methods like the following one:

$query = Sale::where('status', 1);
$query = $query->where('date_time', '<', "2017-05-10 10:10:05");
$totalVolume  = $query->whereHas('vehicle')->sum('vehicles.volume');

and it resulted in the following error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'vehicles.volume' in 'field list' (SQL: select sum(vehicles.volume) as aggregate from sales where status = 1 and date_time < "2017-05-10 10:10:05" and exists (select * from vehicles where sales.vehicle_id = vehicles.id))

hopefully waiting for a solution to 'get the sum of the volume of the sales' using eloquent query.

  • Edited
1
  • I think you should start off by just writing out the raw MySQL query which you would run if you were using Workbench directly. Then, based on that, build the Laravel query. If you can't write the MySQL query then you're probably not ready to attack the Laravel side of things. Commented Sep 14, 2017 at 5:30

2 Answers 2

1

You need to use a join before summing the vehicles.volume column

$totalVolume = Sale::where('status', 1)
    ->where('date_time', '<', "2017-05-10 10:10:05")
    ->join('vehicles', 'vehicles.id', '=', 'sales.vehicle_id')
    ->select(DB::raw('sum(vehicles.volume) as total_volume');
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Martin.. $totalQuantity = $totalQuantityQuery->join('vehicles', 'vehicles.id', '=', 'sales.vehicle_id')->select(\DB::raw('sum(vehicles.volume) as total_volume'))->get() gives an object inside an array.. extracted the result using.. $totalQuantity[0]->total_volume
0
select sum(volume) as aggregate from vehicles INNER JOIN sales ON vehicles.id=sales.vehicle_id 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.