如何在PHP中求和该类属性,以便获得所有类实例的总值? [英] How can I SUM this class attribute in PHP so I get the total value for all class instances?

查看:35
本文介绍了如何在PHP中求和该类属性,以便获得所有类实例的总值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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 的原因.您可以通过在中添加 STAT 关系来轻松获得总和.>类别模型

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆