How can I solve incompatible with sql_mode=only_full_group_by in laravel eloquent?

前端 未结 12 1595
不思量自难忘°
不思量自难忘° 2020-11-29 11:09

My laravel eloquent is like this :

$products = Product::where(\'status\', 1)
            ->where(\'stock\', \'>\', 0)
            ->where(\'category         


        
相关标签:
12条回答
  • 2020-11-29 11:24

    That's because latest versions of MySQL behave like most dbms already do regarding group by clauses; the general rule is

    if you're using group by, all columns in your select must be either present in the group by or aggregated by an aggregation function (sum, count, avg and so on)

    Your current query is grouping by store_id, but since you're selecting everything the rule above is not respected.

    0 讨论(0)
  • 2020-11-29 11:30

    In the .env file ADD variable: DB_STRICT=false.

    And REPLACE in file from the location: config/database.php, next codes 'strict' => true ON 'strict' => (env('DB_STRICT', 'true') === 'true' ? true : false).

    good luck.

    0 讨论(0)
  • 2020-11-29 11:31

    set

    'strict' => false

    in your config/database.php file. In array connections => mysql =>

    in my case I'm using mysql 5.7 Laravel 5.7

    0 讨论(0)
  • 2020-11-29 11:31
     #Have the following method in your helper file
    if (!function_exists('set_sql_mode')) {
    /**
     * @param string $mode
     * @return bool
     */
    function set_sql_mode($mode = '')
    {
        return \DB::statement("SET SQL_MODE=''");
    }
    }
    

    Then call set_sql_mode(''); just before eloquent/query

    0 讨论(0)
  • 2020-11-29 11:34

    I solved this problem by adding the "modes" option and setting only the modes I want to be enabled in config => database.php

    'mysql' => [
        ...
        'modes' => [
            'STRICT_ALL_TABLES',
            'ERROR_FOR_DIVISION_BY_ZERO',
            'NO_ZERO_DATE',
            'NO_ZERO_IN_DATE',
            'NO_AUTO_CREATE_USER',
        ],
    ],
    

    See more details in this tutorial

    0 讨论(0)
  • 2020-11-29 11:37

    What I did as a workaround and to prevent further security issues I make it happen like this:

     public function getLatestModels (){
            \DB::statement("SET SQL_MODE=''");
            $latestInserted = Glasses::with('store.deliveryType','glassesHasTags','glassesHasColors','glassesHasSizes','glassesHasImages','glassesBrand','glassesMaterial')->whereRaw("store_id in (select distinct store_id from glasses)")->groupBy('store_id')->orderBy('created_at')->take(8)->get();
            \DB::statement("SET SQL_MODE=only_full_group_by");
    
            return $latestInserted;
        }
    

    this is a kind of combination of other answers. Also if you are using "use Illuminate\Support\Facades\DB;" you don't need backslashes in those DB statements above.

    The only disadvantage here is that we are making three calls to db :(

    p.s. As I see @Felipe Pena answer I guess the second statement is unnecessary

    0 讨论(0)
提交回复
热议问题