我想执行一个与 laravel 中所有数据库相关的原始查询。所以我不想指向特定的数据库。我怎样才能在 Laravel 中做到这一点?
这是我的代码:
$sql = 'SELECT table_schema \"DB_Name\",
Round(Sum(data_length + index_length) / 1024 / 1024, 2) \"DB_Size_in_MB\"
FROM information_schema.tables
GROUP BY table_schema';
$dbs_size = DB::statement($sql);
如您所见,我的查询并未指向任何特定的数据库。所以我想我不应该使用 DB::
。我该怎么做?
注意到我当前的代码抛出了这个糟糕的错误:(仅此而已)
Whoops, looks like something went wrong.
首先,您过于随意地使用双引号,这在 MySQL 查询中是不应该发生的。
其次,根据https://laravel.com/docs/5.4/database#running-queries , statement
不返回任何内容。
您有几个选项可以使用多个数据库:
1)原始选择
$sql = 'SELECT table_schema DB_Name,
Round(Sum(data_length + index_length) / 1024 / 1024, 2) DB_Size_in_MB
FROM information_schema.tables
GROUP BY table_schema';
$dbs_size = DB::select($sql);
2) 通过在 config/database.php
中添加条目来配置 laravel 使用该数据库
//other database configs
"information_schema" => [
'driver' => 'mysql',
'database' => 'information_schema',
'username' => 'user',
'password' => 'pass',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => ''
]
然后查询通过:
$dbs_size = DB::connection("information_schema")->table("tables")->groupBy("table_schema")->select(DB::raw("...")); // rest of the query..