php yii-db-Connection类(方法)实例源码

下面列出了php yii-db-Connection 类(方法)源码代码实例,从而了解它的用法。

作者:lichunqian    项目:yii2-confi   
public function init()
 {
     $this->db = Instance::ensure($this->db, Connection::className());
     parent::init();
     // Note the default configuration data value will not store to database.
     $this->data = array_merge($this->loadData(), $this->data);
 }

作者:rajanishtime    项目:basicyi   
/**
  * @param  boolean            $reset whether to clean up the test database
  * @param  boolean            $open  whether to open and populate test database
  * @return \yii\db\Connection
  */
 public function getConnection($reset = true, $open = true)
 {
     if (!$reset && $this->db) {
         return $this->db;
     }
     $db = new \yii\db\Connection();
     $db->dsn = $this->database['dsn'];
     if (isset($this->database['username'])) {
         $db->username = $this->database['username'];
         $db->password = $this->database['password'];
     }
     if (isset($this->database['attributes'])) {
         $db->attributes = $this->database['attributes'];
     }
     if ($open) {
         $db->open();
         $lines = explode(';', file_get_contents($this->database['fixture']));
         foreach ($lines as $line) {
             if (trim($line) !== '') {
                 $db->pdo->exec($line);
             }
         }
     }
     $this->db = $db;
     return $db;
 }

作者:rajanishtime    项目:basicyi   
/**
  * @param  boolean $reset whether to clean up the test database
  * @param  boolean $open whether to open and populate test database
  * @throws \yii\base\InvalidParamException
  * @throws \yii\db\Exception
  * @throws \yii\base\InvalidConfigException
  * @return \yii\db\Connection
  */
 public function getConnection($reset = true, $open = true)
 {
     if (!$reset && $this->db) {
         return $this->db;
     }
     $db = new Connection();
     $db->dsn = $this->database['dsn'];
     if (isset($this->database['username'])) {
         $db->username = $this->database['username'];
         $db->password = $this->database['password'];
     }
     if (isset($this->database['attributes'])) {
         $db->attributes = $this->database['attributes'];
     }
     if ($open) {
         $db->open();
         $lines = explode(';', file_get_contents(\Yii::getAlias('@yii/rbac/schema-' . $this->driverName . '.sql')));
         foreach ($lines as $line) {
             if (trim($line) !== '') {
                 $db->pdo->exec($line);
             }
         }
     }
     $this->db = $db;
     return $db;
 }

作者:pipekun    项目:classe   
public function addUser($ldap)
    {
        $profile = Yii::$app->userHelpers->getUserProfileFromHr($ldap->citizen);
        $profile['moo'] = empty($profile['moo']) ? '' : ' หมู่ ' . $profile['moo'];
        $profile['soi'] = empty($profile['soi']) ? '' : ' ซอย ' . $profile['soi'];
        $profile['street'] = empty($profile['street']) ? '' : ' ถ.' . $profile['street'];
        $profile['district'] = empty($profile['district']) ? '' : ' ต.' . $profile['district'];
        $profile['amphur'] = empty($profile['amphur']) ? '' : ' อ.' . $profile['amphur'];
        $profile['province'] = empty($profile['province']) ? '' : ' จ.' . $profile['province'];
        $profile['zipcode'] = empty($profile['zipcode']) ? '' : ' ' . $profile['zipcode'];
        $user = new User();
        $user->id = $profile['id'];
        $user->username = $this->username;
        $user->email = "{$this->username}@kku.ac.th";
        $user->password_hash = Password::hash($this->password);
        $user->save(false);
        $connection = new Connection(Yii::$app->db);
        $connection->createCommand('INSERT INTO auth_assignment VALUES(:item_name, :user_id, :created_at)', [':item_name' => 'User', ':user_id' => $profile['id'], ':created_at' => time()])->execute();
        $admins = Yii::$app->getModule('user')->admins;
        if (in_array($ldap->username, $admins)) {
            $connection->createCommand('INSERT INTO auth_assignment VALUES(:item_name, :user_id, :created_at)', [':item_name' => 'Administrator', ':user_id' => $profile['id'], ':created_at' => time()])->execute();
        }
        $connection->createCommand('UPDATE profile SET
			name = :name,
			address = :address,
			phone = :phone,
			faculty_id = :faculty_id,
			position_id = :position_id,
			position_type_id = :position_type_id,
			level_id = :level_id,
			division_id = :division_id
			WHERE user_id = :user_id
		', [':name' => "{$profile['title']}{$profile['firstname']} {$profile['lastname']}", ':address' => "{$profile['homeadd']}{$profile['moo']}{$profile['soi']}{$profile['street']}{$profile['district']}{$profile['amphur']}{$profile['province']}{$profile['zipcode']}", ':phone' => isset($profile['telephone']) ? $profile['telephone'] : null, ':faculty_id' => isset($profile['faculty_id']) ? $profile['faculty_id'] : Yii::$app->mappingHelpers->mapFaculty($profile['faculty'])['id'], ':position_id' => isset($profile['position_id']) ? $profile['position_id'] : Yii::$app->mappingHelpers->mapPosition($profile['posi'])['id'], ':position_type_id' => isset($profile['position_type_id']) ? $profile['position_type_id'] : Yii::$app->mappingHelpers->mapPositionType($profile['positype'])['id'], ':level_id' => isset($profile['level_id']) ? $profile['level_id'] : Yii::$app->mappingHelpers->mapLevel($profile['level'])['id'], ':division_id' => isset($profile['division_id']) ? $profile['division_id'] : Yii::$app->mappingHelpers->mapDivision($profile['division'])['id'], ':user_id' => $profile['id']])->execute();
    }

作者:lzpfm    项目:dotplant   
public static function createAdminUser(AdminUser $model, \yii\db\Connection $db)
 {
     $db->createCommand()->insert('{{%user}}', ['username' => $model->username, 'password_hash' => Yii::$app->security->generatePasswordHash($model->password), 'email' => $model->email, 'auth_key' => '', 'create_time' => time(), 'update_time' => time()])->execute();
     $userId = intval($db->lastInsertID);
     $assignmentResult = $db->createCommand()->insert('{{%auth_assignment}}', ['item_name' => 'admin', 'user_id' => $userId])->execute() === 1;
     return $assignmentResult && $userId > 0;
 }

作者:nvs-nv    项目:yii2-test-homewor   
public static function search(array $input)
 {
     $connection = new Connection(['dsn' => 'mysql:host=localhost;dbname=work', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8']);
     $connection->open();
     /**запрос выбирает имя сети, агенства и сумму
      * с группировкой ао агенству и "ИТОГО"
      * из подзапроса суммы с границами по датам.
      * COALESCE() меняет сумму NULL на 0
      */
     $sql = 'SELECT agency_network.agency_network_name, agency.agency_name, COALESCE(sum(t.amount),0) AS sum
             FROM agency_network
             RIGHT JOIN agency
             ON agency_network.agency_network_id = agency.agency_network_id
             LEFT JOIN
               (SELECT amount, date, agency_id
               FROM billing WHERE date BETWEEN :startdate AND :enddate) t
                    ON t.agency_id=agency.agency_id
             GROUP BY agency_name WITH ROLLUP;';
     /*Привязываем параметры с датами, для исключения иньекций*/
     $command = $connection->createCommand($sql)->bindParam(':startdate', $startdate)->bindParam(':enddate', $enddate);
     $startdate = $input[date1];
     $enddate = $input[date2];
     $result = $command->queryAll();
     $connection->close();
     return $result;
 }

作者:ivan-chk    项目:yii2-gii-plu   
/**
  * @param Connection $db
  * @param bool $refresh
  * @return string[]
  */
 public static function getSchemaNames(Connection $db, $refresh = false)
 {
     try {
         $schemaNames = array_diff($db->getSchema()->getSchemaNames($refresh), ['public']);
     } catch (NotSupportedException $e) {
         $schemaNames = [];
     }
     return $schemaNames;
 }

作者:Liv102    项目:cm   
/**
  * @return bool
  */
 public function hasConnect()
 {
     $connection = new Connection(['dsn' => "mysql:host={$this->host};dbname={$this->dbname}", 'username' => $this->username, 'password' => $this->password, 'charset' => $this->charset]);
     try {
         $connection->open();
         return true;
     } catch (\Exception $e) {
         return false;
     }
 }

作者:nagse    项目:bas   
/**
  * Конфиг полученный из БД
  * */
 private function getConfigFromDb()
 {
     $dbConfig = $this->textConfig['components']['db'];
     $connection = new Connection(['dsn' => $dbConfig['dsn'], 'username' => $dbConfig['username'], 'password' => $dbConfig['password']]);
     $connection->open();
     $config = $connection->createCommand('SELECT * FROM settings')->queryAll();
     return ArrayHelper::map($config, 'name', 'value', function ($array) {
         return ArrayHelper::getValue($array, 'category');
     });
 }

作者:smarten    项目:yii2-tmcadmi   
public function init()
 {
     parent::init();
     $host = '127.0.0.1';
     $dbname = 'tmc_test';
     $connection = new Connection(['dsn' => 'mysql:host=' . $host . ';dbname=' . $dbname, 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'tablePrefix' => 't_']);
     $connection->open();
     $this->db = $connection;
     if ($this->cache !== null) {
         $this->cache = Instance::ensure($this->cache, Cache::className());
     }
 }

作者:advance10    项目:yunjiany   
protected function setUp()
 {
     parent::setUp();
     $this->mockApplication();
     Yii::$app->set('db', ['class' => Connection::className(), 'dsn' => 'sqlite::memory:']);
     Yii::$app->db->createCommand()->createTable('session', ['id' => 'string', 'expire' => 'integer', 'data' => 'text', 'user_id' => 'integer'])->execute();
 }

作者:axiles8    项目:yii2-viewgri   
public function init()
 {
     parent::init();
     $db = Instance::ensure($this->db, Connection::className());
     $query = new Query();
     $this->ticket = $query->select(['*'])->from($this->table)->createCommand($db)->queryAll();
 }

作者:rajanishtime    项目:basicyi   
public function testOpenClose()
 {
     $connection = $this->getConnection(false, false);
     $this->assertFalse($connection->isActive);
     $this->assertEquals(null, $connection->pdo);
     $connection->open();
     $this->assertTrue($connection->isActive);
     $this->assertTrue($connection->pdo instanceof \PDO);
     $connection->close();
     $this->assertFalse($connection->isActive);
     $this->assertEquals(null, $connection->pdo);
     $connection = new Connection();
     $connection->dsn = 'unknown::memory:';
     $this->setExpectedException('yii\\db\\Exception');
     $connection->open();
 }

作者:tebazi    项目:yii2-db-seede   
public function __construct($db = 'db')
 {
     $this->db = Instance::ensure($db, Connection::className());
     $this->generator = new Generator();
     $this->dbHelper = new Migration(['db' => $this->db]);
     $this->generatorConfigurator = new GeneratorConfigurator();
 }

作者:didwjdgk    项目:yii2-pur-gma   
public function init()
 {
     parent::init();
     $this->i2db = Instance::ensure($this->i2db, Connection::className());
     $this->infodb = Instance::ensure($this->infodb, Connection::className());
     $this->db46 = Instance::ensure($this->db46, Connection::className());
 }

作者:kilyano    项目:yii   
/**
  * Initializes the migration.
  * This method will set [[db]] to be the 'db' application component, if it is `null`.
  */
 public function init()
 {
     parent::init();
     $this->db = Instance::ensure($this->db, Connection::className());
     $this->db->getSchema()->refresh();
     $this->db->enableSlaves = false;
 }

作者:smarten    项目:yii2-tmcadmi   
/**
  * @inheritdoc
  */
 public static function getDb()
 {
     $host = '127.0.0.1';
     $dbname = 'tmc_test';
     $connection = new Connection(['dsn' => 'mysql:host=' . $host . ';dbname=' . $dbname, 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'tablePrefix' => 't_']);
     $connection->open();
     return $connection;
     //if (Configs::instance()->db !== null) {
     //    echo 'sdfdsf';
     //    exit;
     //    return Configs::instance()->db;
     //} else {
     //    echo 'xxxxx';
     //    exit;
     //    return parent::getDb();
     //}
 }

作者:fonclu    项目:i18   
/**
  * Initializes the DbMessageSource component.
  * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
  * Configured [[cache]] component would also be initialized.
  * @throws InvalidConfigException if [[db]] is invalid or [[cache]] is invalid.
  */
 public function init()
 {
     parent::init();
     $this->db = Instance::ensure($this->db, Connection::className());
     if ($this->enableCaching) {
         $this->cache = Instance::ensure($this->cache, Cache::className());
     }
 }

作者:marley-ph    项目:linuxforu   
/**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     $this->db = Instance::ensure($this->db, Connection::className());
     if (is_string($this->cache)) {
         $this->cache = Yii::$app->get($this->cache, false);
     }
 }

作者:jamban    项目:yii2-schemadum   
/**
  * @inheritdoc
  */
 public function beforeAction($action)
 {
     if (parent::beforeAction($action)) {
         $this->db = Instance::ensure($this->db, Connection::className());
         return true;
     }
     return false;
 }


问题


面经


文章

微信
公众号

扫码关注公众号