Laravel --- 查询字段中使用表达式

比如:

select id, name, count(post) from ...

在laravel中:

$user = $this
    ->select(
            'id',
            'name',
            DB::raw('count(post)')
    )
     ->join(...)
     ->first()

执行后会报错: laravel 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语句放到mysql中可以执行,原因是laravel默认使用严格模式,在config/database.php中关闭

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            '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,
        ],
posted @ 2017-03-29 14:18  涛涛taotao  阅读(2892)  评论(0编辑  收藏  举报