[英]Laravel 4, retrieve data from multiple postgresql-schemas
我正在使用 Laravel 4 进行一个项目,在该项目中我使用了 postgres-db。 公共架构是管理员的主要架构。 所有其他自定义模式均适用于客户端。 所有模式都具有相同的表设置。
但是对于某些客户端,必须检索多个模式的数据。 L4 可以实现吗? 还是我必须编写自定义查询?
这些是我对 db-connection 的设置
'pgsql' => array(
'driver' => 'pgsql',
'host' => 'localhost',
'database' => 'postgres',
'username' => 'postgres',
'password' => 'root',
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public, client1, client2',
),
但是当我执行查询时:
$users = Users::all()
**OR**
$users = DB::select(DB::raw('SELECT * FROM client1.users, client2.users'));
我只是从公众中检索用户。 我是不是错过了什么,或者这对 Laravel 来说是不可能的?
提前致谢
使用 Laravel 相当容易。
在您的配置中:
...
'pgsql2' => array(
'driver' => 'pgsql',
'host' => 'localhost',
'database' => 'postgres',
'username' => 'postgres',
'password' => 'root',
'charset' => 'utf8',
'prefix' => '',
'schema' => 'client1',
),
...
在您的模型中:
// Define your second db connection
protected $connection = 'pgsql2';
// Define your table
protected $table = 'users';
如果还没有测试过这个,所以如果这不起作用:
// Define your table
protected $table = 'client1.users';
在你的模型中。
您不需要在配置中指定其他架构,将其保留为public
。
您的查询是错误的 - 仅此而已。 应该是这样:
SELECT * FROM client1.users UNION ALL SELECT * FROM client2.users
此查询将从两个表中选择所有内容。 您可以根据需要从表中选择UNION ALL
。
您可能想要确定哪个用户在哪个架构中,因此只需在查询中添加一个标识符(变量):
SELECT 1 AS s, * FROM client1.users
UNION ALL
SELECT 2 AS s, * FROM client2.users
UNION ALL
SELECT 3 AS s, * FROM client3.users
输出将如下所示:
| s | id | name |
|---|----|--------|
| 1 | 1 | John |
| 1 | 2 | Lucy |
| 2 | 1 | Robert |
| 3 | 1 | Kelly |
| 3 | 2 | Sam |
你需要使用
'schemas' => 'public, client1, client2'
如果要使用多个模式。
例如,当您使用来自不同模式的过程时。
如果你会使用
'schema' => 'public, client1, client2'
它将选择列表中的第一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.