Search code examples
phparraysoopobjectyii

How can I SUM this class property in PHP so I get the total value for all class instances?


I'm using the PHP MVC framwork, Yii. I have a model called Category that has a HAS_MANY relationship to Product model. Both model classes extend CActiveRecord.

I'm looking for help in understanding some specific ways that OOP is working in PHP.

In my a View for my Category Model, I'm trying to find the total inventory count for the Category. For instance, I could do this:

<?php
$total_inventory = 0;
foreach($category->products as $product)
  $total_inventory = $total_inventory + $product->inventory;
echo $total_inventory;
?>

Why can't I just do this?

<?php echo array_sum($category->products->inventory); ?>

That results in an error: PHP Notice: Trying to get property of non-object.

Then I thought maybe the following would work:

<?php echo array_sum($category->products->getAttribute('inventory')); ?>

However, that results in: Fatal error: Call to a member function getAttribute() on a non-object.

Is it possible to use array_sum() in the way I'm attempting by just changing something slightly, or is it not possible because $category->products is actually an object, not an array? Is that right?

I'm happy to be provided with articles or documentation that help explain what I'm missing.

Thanks


Solution

  • Actually the $category->products is an array of objects. Thats why you cant use array_sum on the object attributes. You can get the sum the easy way by adding a STAT relation in the Category Model

    'total_inventory'=>array(self::STAT, 'Product', 'cat_id','select'=>'SUM(inventory)')
    

    and you can get the total_inventory anywhere by calling $category->total_inventory