Mitul Koradiya
Mitul Koradiya

Reputation: 338

Laravel 5.4 arithmetic operation in model relationship

I have a problem to use constant value with parent table value in relation table.

$cost = 5; 
$product = Product::with(["productPrice" => function($q) use($cost) {
               $q->select("id", "product_id", "price", \DB::Raw("(('"+ $cost + "' * product.weight) / product.pack_size) + price as cost"));
           }])->select("id", "sku", "pack_size", "image" ,'weight')->get();

in Mysql,

select product.id, product.sku, product.pack_size, product.image, product.weight, product_price.id as product_price_id, product_price.price,(($cost * product.weight)/product.pack_size) + product_price.price as cost from product join product_price on product.id = product_price.product_id

Query working ready but how to use in laravel model relationship ?

Upvotes: 1

Views: 838

Answers (1)

Radu
Radu

Reputation: 1031

I had a similar problem and I temporarily solved using the DB facade and using DB::raw for inserting constants .... Hope it helps ... Something like that:

 $query= DB::table('product')->
        ->join ('product_price','product.id','=','product_price.product_id')->
        ->select('product.id',
            'product.sku',
            ' product.pack_size',
            'product.image',
            'product.weight',
            'product_price.id as product_price_id',
            DB::raw('($cost * product.weight)/product.pack_size)'),
            'product_price.price as cost from product',
            'product_price.price')
        )->get();

Upvotes: 1

Related Questions