Search code examples
phplaraveleloquentlaravel-5.7yajra-datatable

Laravel math operations on SELECT statement


I'm working on a query that has to retrive some columns from diferents tables and do the maths to calculate a product price based on the amount of needed material and the amount of work hours.

On one table I have the hour price (the price is set by the office location), on another table I have the material price (the materal price is set by material type of and the office location) and finally I have the products table where I set the total material and working hours needed.

The math I need to do is the following:

Total price = (price per hour * total needed hours) + (price per material * total needed hours)

This is the query I'm working on:

        // working hour price
        $mo = WorkForce::where('company_id', session()->get('currentCompany.id'))->orderBy('created_at', 'desc')->first()->get();

        // Material price
        $mt = MaterialPrice::where('company_id', session()->get('currentCompany.id'))->where('type_id', 4)->orderBy('created_at', 'desc')->first()->get();

$query = $model->newQuery()
            ->leftJoin('materials', 'products.material_id', '=', 'materials.id')
            ->leftJoin('vehicles', 'products.vehicle_id', '=', 'vehicles.id')
            ->leftJoin('parts', 'products.part_id', '=', 'parts.id')
            ->select(
                'products.id as id',
                'products.name as product_name',
                'parts.part_name as part_name',
                'materials.public_name as material',
                'vehicles.name as vehicle',
                "(products.labour * $mo[0]) + (products.premium_modifier * $mt[0]) as price"
            )
            ->where('products.company_owner_id', session()->get('currentCompany.id'))
            ->orWhere('products.company_owner_id', null);

This query it's made to poblate a jquery datatable with Yajra\DataTables\EloquentDataTable's module. Now I see all the other columns fine but the column that should show the total price is empty and I don't see error messages. I'm not sure that Laravel allows this kind of maths on selects though.

In case it may be important we work with Laravel 5.7


Solution

  • Finally I found a solution. For my case in particular on the DataTable class I work with I have a fuction defined that allows me to add columns 'on the fly' to add buttons and links generated from the table columns data.

    Using this function I added a new column at the end of the table with the math operation's result.

    Not sure if there's out a lot of projects with this same configuration though.