PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 21, 2022

[FIXED] Laravel Query Builder - Use sum method on a generated attribute

 February 21, 2022     eloquent, laravel, laravel-query-builder, mysql, php     No comments   

Issue

Let's say I have these 2 models:

Order Model:

  • id
  • state (incomplete, complete)

Item Model:

  • id
  • order_id
  • type
  • is_worthy.

.

/**
 * Returns the item's price according to its worthy
 */
public function getPriceAttribute()
{
    return $this->is_worthy ? 100 : 10; // $
}

So far so good.

Now I want to summarize the price of the complete orders. So I'm doing this:

App\Item::whereHas('order', function ($query) {
    $query->where('state', 'complete');
})->sum('price')

But the thing is, that I don't have in my items table the column price. Because the price attribute is generated in the Model.

So my question is, how can I summarize price of the complete orders?


Solution

There are 2 ways to do this:

1. Have PHP do all the work

$items = App\Item::whereHas('order', function ($query) {
    $query->where('state', 'complete');
})->get();
$sum = $items->sum(function($item) {
    return $item->price;
});
// In Laravel 5.4, you can replace the last line with $sum = $items->sum->price;

2. Have SQL do all the work

$items = App\Item::whereHas('order', function ($query) {
    $query->where('state', 'complete');
})->select('*', DB::raw('IF(is_worthy, 100, 10) as price'))->sum('price');


Answered By - Paras
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing