【问题标题】:DB::select returning different results than mysql command lineDB::select 返回与 mysql 命令行不同的结果
【发布时间】:2016-05-27 16:26:25
【问题描述】:

我正在尝试重命名 MySQL 数据库中的某些列,但不幸的是,该表包含 enum,因此 doctrine\dbal 会引发错误。我决定使用原始 sql 编写自己的重命名函数,但是我正在执行的一些检查失败了,我不知道为什么。

当我在 MySQL CLI 中时,我运行这个查询:

select table_name from information_schema where table_name = "my_table" and table_schema = "my_schema";

正如预期的那样,这将返回带有表名的一行。所以我想在我的迁移中,我可以这样做:

$exists = Schema::hasTable('my_table');

但是返回了false。很奇怪,我想,所以让我们把整个 Schema 排除在外,直接尝试针对 information_schema 的 sql。

$result = DB::select('select table_name from information_schema where table_name = ? and table_schema = ?', ['my_table', 'my_schema']);

但是,当我运行该语句时,$result 的值是[]。我想也许编译的sql可能是错误的,所以我dumped out了来自DB::getQueryLog()的返回,但看起来都是正确的:

array:1 [
    0 => array:3 [
        "query" => "select table_name from information_schema.tables where table_name = ? and table_schema = ?;"
        "bindings" => array:2 [
            0 => "my_table"
            1 => "my_schema"
        ]
        "time" => 0.01
    ]
]

我应该指出,当我运行 php artisan tinker 并运行相同的 DB::select() 语句时,我得到了我正在寻找的结果,所以它似乎不适用于迁移文件。

我很茫然。为什么DB::select() 会返回与在 MySQL CLI 上运行完全相同的查询不同的结果?

【问题讨论】:

    标签: php mysql laravel-5 eloquent laravel-5.2


    【解决方案1】:

    请使用 DB:raw('select table_name from information_schema where table_name = "my_table" and table_schema = "my_schema"');

    【讨论】:

    • 不行:dd(DB::select(DB::raw('select * from information_schema.tables where table_schema = "my_schema"'))); 返回[]
    【解决方案2】:

    我目前有一个解决方法。我在我的config/database.php 文件中创建了第二个相同的连接配置文件,它具有与my_schema 相同的连接信息,除了我将database 更改为information_schema。在我的迁移中,我正在使用以下内容:

    DB::connection('my_informationschema')->select('select table_name from information_schema where table_name = ? and table_schema = ?', ['my_table', 'my_schema']);
    

    这就是返回我需要的东西。所以看起来应用程序可以让您在使用原始查询时快速轻松地使用模式,除非您在迁移中?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-10
      • 1970-01-01
      • 2017-12-28
      • 1970-01-01
      • 2021-04-22
      • 1970-01-01
      • 2014-08-04
      相关资源
      最近更新 更多