简体   繁体   中英

Multiple database connection in Doctrine2 and Zend framework

I am currently working on an application which is built using ZF 1.11.3 - Doctrine2 is the ORM component used. I need to use multiple databases. Within the application.ini file, I have set the database connections as follows:

resources.doctrine.dbal.connections.default.parameters.dbname   = "db_name_one"
resources.doctrine.dbal.connections.secondary.parameters.dbname   = "db_name_two"

How would I associate the Doctrine2 entity classes based on the second database connection with that connection: For example, if I have an entity class from the second connection as:

/*
   * @Entity
   * @Table(name="tableOnSecondDatabase")
   */
  Class EntityFromSecond
  {

How will Doctrine2/ZF know what entity classes are mapped to a database? Thanks for helping.

I don't thinl you can bind an entity to specific connection, it wouldn't make sense in the Doctrine 2 architecture.

What you can do, on the other hand is to have two EntityManagers, each with different connection options. You must decide in your business logic, which entity is treated by which connection manager.

edit Doctrine 2 does not support cross database joins in the sense of having two distinct connections and joining across them, AFAIK. I can't even imagine, how that would work on the PHP PDO level. What Vijay suggested for one based around Doctrine 1 and second, that's not exactly cross database join, as Doctrine 1 executes 2 queries and merges the results itself, which is not optimal performance-wise.

What you could do, on the other hand, is to have one connection, which can access both databases (that is, if they're on the same DB server), or schemas, if you're on say Postgres, and define your entities as such:

//defining first entity
@Entity
@Table(firstSchema.table_name)
class MyEntity

//defining second entity

@Entity
@Table(secondSchema.table_name)
class SecondEntity

This should work, I believe

If your are using two different databases for the same application and they are independently serving different modules in your application you can do plugin level injection and choose correct db connection according to the request.

In the following link multiple databases are handled using separate connections.

http://stuf.ro/using-multiple-databases-in-doctrine/

If you are having association between two databases and need to retrieve data after joining tables from two of these database you can create doctrine entity class by specifying dbName.tableName.columnName. It will be little tricky, but for further reference look at the following link:

http://www.doctrine-project.org/blog/cross-database-joins

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM