How can I use this class attribute in PHP to get a common value for all instances of the class?

I am using the PHP MVC framework, Yii. I have a model called Category that has a HAS_MANY relationship with the Product model. Both model classes extend CActiveRecord .

I am looking for help in understanding some of the specific ways that OOP works in PHP.

In my view for my category model, I am trying to find the total inventory for a category. For example, 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 do this?

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

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

Then I thought the following might work:

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

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

Is it possible to use array_sum() as I try, just to change something, or is it impossible, because $category->products is actually an object, not an array? Is it correct?

I am glad that I was provided with articles or documentation that will help explain what I am missing.

thanks

0
source share
1 answer

Actually $category->products is an array of objects. That is why you cannot use array_sum for object attributes. You can easily get the amount by adding a STAT relation to the Category Model

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

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

+1
source

All Articles