我有这个代码,显示所有每日取消订阅的用户..
public function getdailyUnSubs($modelName,$op){
$currentDate = date('Ymd');
$criteria = new CDbCriteria;
$criteria->select = 'app_unsubs,sms_unsubs';
$criteria->order = 'date DESC';
$criteria->limit = 1;
$criteria->offset = 0;
$Subscriber = $modelName::model()->find($criteria);
$totalunSubs = $Subscriber['app_unsubs']+$Subscriber['sms_unsubs'];
return $totalunSubs;
}
但是现在我想要获得所有未订阅的用户。我想要所有未订阅用户的总和。
这是我的代码,但它无效。
public function getTotalUnSubs($modelName,$op){
$criteria = new CDbCriteria;
$criteria->select ='sum(app_unsubs) as appunsubs, sum(sms_unsubs) as smsunsubs';
$Subscriber = $modelName::model()->find($criteria);
$totalunSubs = $Subscriber['appunsubs']+$Subscriber['smsunsubs'];
return $totalunSubs;
}
说appunsubs
和smsunsubs
未定义。
即使我将代码更改为
$criteria->select ='(sum(app_unsubs)+ sum(sms_unsubs)) as totalunsubs';
和
$totalunSubs = $Subscriber['totalunsubs'];
仍然说totalunsubs
未定义。
答案 0 :(得分:2)
您有未定义的appunsubs
和smsunsubs
,因为您的$modelName
模型类中没有类似的字段。要获取数据,您可以根据条件创建查询,并使用Yii::app()->db->createCommand($sql)->queryRow()
执行此查询。看看这段代码:
public function getTotalUnSubs($modelName,$op)
{
$criteria = new CDbCriteria;
$criteria->select ='sum(app_unsubs) as appunsubs, sum(sms_unsubs) as smsunsubs';
//creating proper SQL
$sql = Yii::app()->db->commandBuilder->createFindCommand($modelName, $criteria)->getText();
//fetching data based on created SQL stored in $sql variable
$Subscriber = Yii::app()->db->createCommand($sql)->queryRow();
$totalunSubs = $Subscriber['appunsubs']+$Subscriber['smsunsubs'];
return $totalunSubs;
}
答案 1 :(得分:1)
我认为您必须将分组依据设置到您的查询中。
所以代码就像这样。
Imports System.ComponentModel
Public Class UserControl1
Dim _Range As UShort = 100
Private Sub UserControl1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label1.Text = _Range
End Sub
Public Function ShouldSerializeTBValueRange() As Boolean
Return _Range <> 200
End Function
Public Sub ResetTBValueRange()
_Range = 200
Label1.Text = _Range
End Sub
Public Property TBValueRange As UShort
Get
Return _Range
End Get
Set(ByVal Steps As UShort)
_Range = Steps
Label1.Text = _Range
End Set
End Property
End Class
答案 2 :(得分:0)
简单的解决方案是将公共或受保护的变量名称作为总和添加到模型中。我建议使用它,因为我称之为“子模型” ...
class Summary extends CActiveRecord {
public $total;
}
class Item extends Summary {
...
}
然后您可以在条件中自由使用计数或总和,它们将在使用find,findAll等检索的模型中显示为变量。
$criteria = new CDbCriteria();
$criteria->select = "count(id) as total,type,lang,source";
$criteria->group = "lang,source,type";
$result = Item::model()->findAll($criteria);
结果为:(例如)
array(1) {
[0]=>
object(Item)#48 (12) {
["total"]=>
string(2) "50"
这些子模型非常适合将函数,关系和其他内容保留在其中,就好像该类需要从Gii中自动生成一样,您只需要用extensions SubmodelName ...替换extends CActiveRecord ...
此外,这些年来,我已经开发了Base(模型)来设置我一般所需的所有内容(登录用户的user_id,检查日期的格式正确等)