Doctrine 中定义多个模型管理器和数据库链接
我们在项目中可能会遇到连接两个数据库。那么在symfony中该怎么来执行呢?
下面的代码演示了怎么执行多个链接
doctrine的详细配置:https://symfony.com/doc/master/reference/c...
在app/config/routing.yml中的doctrine配置中做以下配置。
doctrine:
dbal:
default_connection: default
connections:
default:
driver: pdo_mysql
host: '%database_host%'
port: '%database_port%'
dbname: '%database_name%'
user: '%database_user%'
password: '%database_password%'
charset: UTF8
customer:
driver: pdo_mysql
host: '%database_host2%'
port: '%database_port2%'
dbname: '%database_name2%'
user: '%database_user2%'
password: '%database_password2%'
charset: UTF8
orm:
default_entity_manager: default
entity_managers:
default:
connection: default
mappings:
AppBundle: ~
AcmeStoreBundle: ~
customer:
connection: customer
mappings:
AcmeCustomerBundle: ~
在处理多个管理器中,执行数据库操作命令的时候:
只能创建default
php bin/console doctrine:database:create
创建customer
php bin/console doctrine:database:create --connection=customer
在获取doctrine manager的时候,
public function indexAction()
{
// 这三个返回 "default" 实体管理器
$em = $this->get('doctrine')->getManager();
$em = $this->get('doctrine')->getManager('default');
$em = $this->get('doctrine.orm.default_entity_manager');
// 这两个返回 "customer" 实体管理器
$customerEm = $this->get('doctrine')->getManager('customer');
$customerEm = $this->get('doctrine.orm.customer_entity_manager');
}
在从Repository中获得的时候。
public function indexAction()
{
// 获取Repository中的"default"
$products = $this->get('doctrine')
->getRepository('AcmeStoreBundle:Product')
->findAll()
;
// 获取Repository中的"default"
$products = $this->get('doctrine')
->getRepository('AcmeStoreBundle:Product', 'default')
->findAll()
;
// 获取Repository中的"customer"
$customers = $this->get('doctrine')
->getRepository('AcmeCustomerBundle:Customer', 'customer')
->findAll()
;
}
在symfony中使用doctrine的DBAL
Doctrine 数据库抽象层(DBAL)是一个抽象层面,位于 PDO 的顶端,并且提供一个直观的和灵活的 API,用于与最流行的关系数据库进行通信。换句话说,DBAL 库使执行查询和执行其他数据库操作很容易。
快速的做出最基本的配置。
# app/config/config.yml
doctrine:
dbal:
driver: pdo_mysql
dbname: Symfony
user: root
password: null
charset: UTF8
server_version: 5.6
具体配置传送门:https://symfony.com/doc/master/reference/c...
DBAL的文档:http://docs.doctrine-project.org/projects/...
然后我们可以获取访问 database_connection 服务来访问 Doctrine DBAL 连接:
public function indexAction(Request $request)
{
$conn = $request->get('database_connection');
$users = $conn->fetchAll('SELECT * FROM users');
}
这样子喜欢这种写法的伙伴们更便捷了。
不过我个人不建议初学者在学习期间DBAL ORM混合着写。建议先使用一种方法来操作。等到以后熟练掌控再成为双贱合璧的大神。