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

Saturday, February 26, 2022

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

 February 26, 2022     arrays, object, oop, php, yii     No comments   

Issue

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



Answered By - dInGd0nG
  • 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