Yii:Cactiverecord :: findall()需要从不同的数据库中检索并返回值

时间:2016-09-07 05:43:16

标签: php yii

我在不同的数据库中有记录。当调用findall方法时,我需要返回所有这些。

我在模型

中有getDbConnection()函数
 public function getDbConnection($db='')
 {      
    if($db!='')
    {
      $connection = Yii::app()->getComponent($db);
      return $connection;

    }

    if(self::$db!==null)
        return self::$db;
    else
    {
        self::$db=Yii::app()->getDb();

        if(self::$db instanceof CDbConnection)
            return self::$db;
        else
            throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
    }
  }

在CactiveRecord.php中

public function getCommandBuilder($db)
{
    return $this->getDbConnection($db)->getSchema()->getCommandBuilder($db);
}


public function findAll($condition='',$params=array())
{
       Yii::trace(get_class($this).'.findAll()','system.db.ar.CActiveRecord');

  $dbconnection = array('db','dbmobisite');//db abd dbmobisite are component names in protected/config/main.php
  $returnall = array();
  foreach($dbconnection as $db)
  {     
        $criteria=$this->getCommandBuilder($db)->createCriteria($condition,$params);
        $return = $this->query($criteria,true);
        foreach($return as $values)
        {
            array_push($returnall,$values);
        }
    }

    return $returnall;
}

但是我收到以下错误:

  

缺少CActiveRecord :: getCommandBuilder()的参数1,在第1358行的/home/jrickby/public_html/hastings.pro/framework/db/ar/CActiveRecord.php中调用并定义了

它说错误在这个函数中

public function getCommandBuilder($db)
{
    return $this->getDbConnection($db)->getSchema()->getCommandBuilder($db);
}

我不知道如何解决这个问题,请帮忙

1 个答案:

答案 0 :(得分:0)

您可以在配置文件中创建数据库配置数组,并将模型与正确的数据库配置相关联。

配置/ main.php

'components' => [
    'db' => [
        ...
    ],
    'anotherDb' => [
        ...
    ],
],

覆盖anotherDb

中存在的模型中的getDbConnection()
public function getDbConnection()
{
    return Yii::app()->anotherDb;
}