Phalcon 框架 配置多个数据库连接

一共涉及到三个文件

1:数据库的配置文件 2:框架的配置文件 引入数据库配置 3:模型 需要指定连接信息

1:在config.php 文件中配置好数据库的链接信息 我这里连接了三个库

<?php
return [
'database' => [
'adapter' => 'Mysql',
'host' => '127.0.0.1',
'username' => 'root',
'password' => 'root',
'dbname' => 'msg_db',
'charset' => 'utf8mb4',
],


'curtidb' => [
'adapter' => 'Mysql',
'host' => '127.0.0.1',
'username' => 'root',
'password' => 'root',
'dbname' => 'msg_curti',
'charset' => 'utf8mb4',
],

 

'ygdb' => [
'adapter' => 'Mysql',
'host' => '127.0.0.1',
'username' => 'root',
'password' => 'root',
'dbname' => 'txgl',
'charset' => 'utf8mb4',
],

];


2: 在services.php 文件中 指定连接其中一个数据库配置


$di->setShared('db', function () use ($config) {
return new DbAdapter($config->database->toArray());
});


$di->setShared('curtidb', function () use ($config) {
return new DbAdapter($config->curtidb->toArray());
});

 

$di->setShared('ygdb', function () use ($config) {
return new DbAdapter($config->ygdb->toArray());
});

3:在模型里 指定使用哪个数据库 这里指定的是ygdb库

<?php

namespace Common\Models;

use Phalcon\Validation;
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\StringLength;
use Phalcon\Validation\Validator\Uniqueness;
use Phalcon\Validation\Exception;


class YPedidolist extends Model
{

/**
* Initialize method for model.
*/
public function initialize()
{
$this->setConnectionService('ygdb');
}

/**
* Returns table name mapped in the model.
*
* @return string
*/
public function getSource()
{
return 'pedidolist';
}

static public function getPkCol(){
return 'id';
}

}

posted @ 2022-11-30 14:39  niniko  阅读(133)  评论(0编辑  收藏  举报