Jesse Jesbu Sun Oct 06 08:29:02 -0400 2013

Subject: Selecting sum of column rows from other table

Hello,

I'm pretty new with this ActiveRecord, and now wondering, is there way to get sum of column rows from other table than actual model is?

Example. I've one db-table called "bills", that has id field as primary key.
Then I've another table that has bills_items, that also has id field as primary key, also field for which bill that row belongs, and of course amount of item, and price of one item.

Now I'd like to retrieve final price of bill for bill listing. Is there any other ways than retrieve all items of that bill, and sum rows (amount*price) together in PHP, or can I do it somehow with activerecord?

Thanks for help!


Bill Zhao Mon Oct 07 22:43:55 -0400 2013
$total = array_sum(ActiveRecord\collect($bill->items,function($item)
{
 return $item->amount * $item->price;
}); 
Jesse Jesbu Tue Oct 08 14:27:39 -0400 2013

Bill Zhao wrote:

[...]

Hi, thanks for answer, but I'm not really getting where to place this? In model?

Bill Zhao Fri Oct 11 05:25:44 -0400 2013
#bill.php
class Bill extends Activerecord\Model
{
   public function total()
  {
    return array_sum(ActiveRecord\collect($bill->items,function($item)
    {
    return $item->amount * $item->price;
    }); 
  }
}
$bill = Bill::last();
$total = $bill->total();

(1-3/3)