0

我有一个包含 7 列和 400 条记录的数据表。其中之一是预算。我想按预算对 400 行进行分组,以便得到这样的数组:

[budget]=>array(
          [0]=>array(
              [column1]=>'1',
              [column2]=>'sand'
              ),
          [1]=>array(
              [column1]=>'2',
              [column2]=>'clay'
              )
          )
[budget2]=>array(
          [0]=>array(
              [column1]=>'3',
              [column2]=>'silt'
              ),
          [1]=>array(
              [column1]=>'4',
              [column2]=>'stone'
              )
          )

到目前为止,我一直在玩 Yii 的 CdbCommand 和 CdbDataReader 以及 PHP 的 PDOStatement,但没有任何工作正常。我尝试了以下代码

public function actionBidCostByBudget(){

        $command = Yii::app()->db
        ->createCommand()
        ->Select('*')
        ->From('bid_cost')
        # ->Query()
        ;
        echo '<pre>';
        echo get_class($command);
        $pdostatement=$command->getPdoStatement();
        if($pdostatement) echo get_class($pdostatement);
        # print_r($statement->fetchall(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));
        # print_r($command->readall());
        # print_r($statement->fetch());
        # $columnsArray = BidCost::attributeLabels();

        //print_r($rowsArray);
        //$this->layout='\\layout';
}

print_r 的尝试全部打印出来。getPdoStatement 等于什么。我一直在尝试按照 Php.net 网站使用 PDO::FETCH_COLUMN|PDO::FETCH_GROUP ,但它也不起作用,因为我什么也没得到。

4

2 回答 2

0

好吧,最重要的是我无法通过 Yii 找到正确的方法,所以我用更实际的方法做到了。

我做的第一件事基本上是通过 Yii启动数据库连接。

$command = Yii::app()->db   //outputs CDbConnnection

我做的下一件事是从连接中获取一个 PDO 类:

$pdoinstance = $command->getPdoInstance();  //outputs PDO class

从这一点来看,它是从 PHP.net 获得的帮助以及该论坛上发布的另一个问题:

$pdostatement=$pdoinstance->prepare('SELECT BUDGET_CODE, 
PAY_ITEM, ITEM, DESCRIPTION FROM bidcost');
$pdostatement->execute();
//default fetch mode could not be set
# $pdostatement->setfetchmode(PDO::FETCH_GROUP|PDO::FETCH_ASSOC); 
//returns array
$testarray=$pdostatement->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC); 
于 2013-06-29T19:28:08.460 回答
0

One of Yii's strengths is it's ActiveRecord, so why not use it?

Make your budget to a separate table (so you can generate a model from it). Reference it from your "datatable".

CREATE TABLE budget (
    id INTEGER PRIMARY KEY,
    name TEXT
);

CREATE TABLE datatable(
    column1 TEXT,
    column2 TEXT,
    ...
    budget_id INTEGER,
    FOREIGN KEY(budget_id) REFERENCES budget(id)
);

Next generate models with Gii, and now you can use your newly made relations like this:

$budget = Budget::model()->findByAttributes( ["name"=>"budget2"] );
foreach( $budget->datatables as $dt ) {
    echo $dt->column1;
    echo $dt->column2;
}

(I know. Not the array you asked for. Sorry if I'm way off with this.)

于 2013-06-29T02:00:33.233 回答