如何在 PHP 中对此类属性求和,以便获得所有类实例的总值? [英] How can I SUM this class property in PHP so I get the total value for all class instances?
问题描述
我正在使用 PHP MVC 框架 Yii.我有一个名为 Category 的模型,它与 Product 模型具有 HAS_MANY
关系.两个模型类都扩展了 CActiveRecord.
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.
我正在寻求帮助以了解 OOP 在 PHP 中的某些具体工作方式.
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;
?>
为什么我不能这样做?
<?php echo array_sum($category->products->inventory); ?>
这会导致一个错误:PHP 注意:试图获取非对象的属性
.
然后我想也许以下方法可行:
Then I thought maybe the following would work:
<?php echo array_sum($category->products->getAttribute('inventory')); ?>
然而,这会导致:致命错误:在非对象上调用成员函数 getAttribute()
.
是否可以像我尝试的那样通过稍微改变一些东西来使用 array_sum()
,或者是不可能的,因为 $category->products
实际上是一个对象,而不是一个数组?是吗?
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.
谢谢
推荐答案
实际上 $category->products
是一个对象数组.这就是你不能在对象属性上使用 array_sum
的原因.您可以通过在 类别
型号
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)')
并且您可以通过调用 $category->total_inventory
这篇关于如何在 PHP 中对此类属性求和,以便获得所有类实例的总值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!