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,
        ],


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM