MySQL查询在Laravel中不起作用,但在mysqli_ *下可以正常工作

时间:2019-03-06 18:56:53

标签: php mysql laravel

我有一个mysql查询:

SELECT MAX(CAST(REPLACE(name,'test','') AS SIGNED)) FROM `accts` WHERE `name` LIKE 'test%';

如果我在MySQL控制台中运行查询,它将执行。

如果我使用 PHP

中的 mysqli_query 执行此查询
mysqli_query($connection, "SELECT max(cast(replace(name,'test','') as signed)) FROM accts WHERE name LIKE '$test%'")

它执行。

如果我在laravel中运行它:

DB::connection('db')
                ->table('accts')
                ->select(DB::raw("max(cast(replace(name,'test','') as signed))"))
                ->where('name', 'like',  "'$test%'")
                ->get();

它抛出一个错误:

SQLSTATE[42000]: Syntax error or access violation: 1140 Mixing of GROUP columns (MIN(), MAX(), COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause (SQL: select max(cast(replace(name,'test','') as signed)) from `accts` where `name` like 'test%')

有人知道发生了什么吗?该错误看起来像是来自服务器,但服务器查询没有问题。 laravel如何执行查询是否存在问题?

1 个答案:

答案 0 :(得分:1)

您的问题必须与数据库配置有关

在您的config/database.php中,关闭严格模式('strict' => false,)。

示例:

'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'strict' => false,
        'engine' => null,
    ],

参考:

Laravel Eloquent Where

Syntax error or access violation: 1140 Mixing of GROUP columns laravel