Zend Framework 2-连接不同数据库和架构中的表 [英] Zend Framework 2 - Join tables in different databases and schemas

查看:40
本文介绍了Zend Framework 2-连接不同数据库和架构中的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Zend Framework 2中,当我想在不同数据库表之间建立联接时,必须使用 \ Zend \ Db \ Sql \ TableIdentifier 类,以避免错误的转义.

In Zend Framework 2 when I want to make a join between different database tables I have to use the \Zend\Db\Sql\TableIdentifier class to avoid an incorrect escaping.

如果我这样做:

$select->join(['B' => 'database2.table2'], 'A.id = B.id');

它呈现为:

SELECT [..] FROM "table" as "A" INNER JOIN "database2.table2" ON [...]

这会导致引用错误"database2.table2"

要解决这种情况,我可以做:

To solve this situation I can do:

$tbl2 = new \Zend\Db\Sql\TableIdentifier('table2', 'database2');
$select->join(['B' => $tbl2], 'A.id = B.id');

通过这种方式引用是正确的"database2"."table2"

In this way the quoting is correct "database2"."table2"

但是,如果我必须指定数据库以及架构,该怎么办?(例如,在ms sql服务器中)

But how can I do if I have to specify the database and also the schema? (for example in ms sql server)

所需的结果是"database2"."dbo"."table2"

推荐答案

当您使用表网关类的方法时,可以执行以下操作:

When you're in a method of a table gateway class, you can do this:

$table2 = new Zend\Db\Sql\TableIdentifier('table2', 'schema_name'); 
$select = $this->tableGateway->getSql()->select()
->join($table2, 'table1.field = table2.field', ['fields_from_table2'], 'INNER');

$sql = new Sql($this->tableGateway->getAdapter());
$selectString = $sql->buildSqlString($select);
$result = $adapter->query($selectString, $adapter::QUERY_MODE_EXECUTE);

如果尝试从字面上编写 database.table ,则不会让Zend知道 database.table 是什么.因此,Zend将把当前定义的数据库中的当前数据库放入Module.php的当前表网关工厂使用的适配器中,编写 current_database.database.table .

If you try to write database.table literally, you don't let Zend to know that a database.table is what it is. Therefore, Zend will put the current database defined in the adapter that is used from current table gateway factory from Module.php, writing current_database.database.table.

此问题与 zf2进行联接的主题相同在两个不同的数据库之间

这篇关于Zend Framework 2-连接不同数据库和架构中的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆