Yii Framework 如何统计记录?

How to do a count of records in Yii Framework?

我有两个 table 'Company' 和 'Department'

CREATE TABLE Department (
id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 
deptName VARCHAR(40),
CompanyId TINYINT UNSIGNED NOT NULL,
FOREIGN KEY (CompanyId) REFERENCES Companies(id) ON DELETE CASCADE,
UNIQUE (deptName))

CREATE TABLE Company (
id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
companyName VARCHAR(40),
email VARCHAR(60),
UNIQUE (companyName))

我正在创建新记录、更新、删除和显示所有记录。但是现在我想显示特定公司的部门总数。例如:

A公司有3个部门 B公司有2个部门。 我只想计算部门的数量。输出电流为

ID: 1   
Company Name: CompanyA  
Email: Contact@companyA.com

但我想展示

ID: 1   
Company Name: CompanyA  
Email: Contact@companyA.com
Total Department: 3 //it can be different

这只是一条记录,但我的输出中显示了很多公司。部门有不同 table..我必须更改哪个代码才能显示部门总数

我在 Gii 中使用 CRUD 操作创建的控制器 'CompanyController' 和 'DepartmentController' 具有简单的功能..

这是我的index.php

<h1>Companies</h1>

<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
)); ?>

这是我的 _view 文件

<div class="view">

<b><?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:</b>
<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>
<br />

<b><?php echo CHtml::encode($data->getAttributeLabel('companyName')); ?>:</b>
<?php echo CHtml::encode($data->companyName); ?>

我不确定应该在哪里计算数据。我已经在部门控制器中编写了一个计算部门总数的函数,但它在这里不起作用是我的函数

public function totalDept()
{
    $CompanyId=1;
    $totalDept=Department::model()->findAll($CompanyId);
    $numberOfDept=count($totalDept);
    if ($numberOfDept> 0) {
        echo "There are" .$numberOfDept. "in this company";
    } else {
        echo 'This company has No Department so far...';
    }

}

当我在我的视图中显示时它不起作用..它说 属性 Department.totaldept 未定义

<b><?php echo CHtml::encode($data->getAttributeLabel('Total Departments')); ?>:</b>
<?php echo CHtml::encode(Department::model()->totalDept); ?>
<br />

无论我尝试做的是正确的方法还是做错了,我只是 yii 的新手,只是想学习 yii..

按照 Yii 的惯例。您应该首先在模型文件中定义 CompanyDepartment 之间的关系。

在你的例子中——公司有很多部门,所以在你的公司模型中,定义如下关系(假设你使用的是 Yii 1.x)

public function relations()
{
    return array(
        // other relationships
        'departments' => array(self::HAS_MANY, 'Department', 'CompanyId'),
    );
}

定义此关系后,您可以在 _view 文件中获取公司部门的计数,如下所示。

echo count($data->departments);

您可以简单地在公司 AR class 的 relations() 方法中定义一个 "attribute",它将执行统计查询(默认情况下是计数)。您可以通过使用 "self::STAT" 作为关系类型来做到这一点,请参见下面的示例:

public function relations()
{
    return array(
        // other relationships
        'totalOfdepartments' => array(self::STAT, 'Department', 'CompanyId'),
    );
}

您可以在这里获得更多信息:http://www.yiiframework.com/doc/guide/1.1/en/database.arr#statistical-query