i have two pointages and chantiers table between them belongsTo relationship, I want to display the chantiers name and the sum of sold for each chantier I tried this function, but it gives me error
$dataP = DB::table('chantiers')
->leftJoin('pointages','pointages.chantier_id','chantiers.id')
->selectRaw('COALESCE(SUM(pointages.sold),0) as sold,chantiers.chantier')
->groupBy('pointages.chantier_id')
->get();
pointages table
chantiers table
Your mysql version is 5.7+, so check this reference
MySQL 5.7.5 and up implements detection of functional dependence. If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list
Check the config/database.php, if your mysql configuration strict => true
, you need to disabled the ONLY_FULL_GROUP_BY
, add modes
like this:
'mysql' => [
'driver' => 'mysql',
...
'strict' => true,
'engine' => null,
'modes' => [
//'ONLY_FULL_GROUP_BY',
'STRICT_TRANS_TABLES',
'NO_ZERO_IN_DATE',
'NO_ZERO_DATE',
'ERROR_FOR_DIVISION_BY_ZERO',
'NO_AUTO_CREATE_USER',
'NO_ENGINE_SUBSTITUTION'
],
],
PS: set strict => false
can work too, but disabling it make your app unsecured.
Use ANY_VALUE :
This function is useful for GROUP BY queries when the ONLY_FULL_GROUP_BY SQL mode is enabled, for cases when MySQL rejects a query that you know is valid for reasons that MySQL cannot determine. The function return value and type are the same as the return value and type of its argument, but the function result is not checked for the ONLY_FULL_GROUP_BY SQL mode.
$dataP = DB::table('chantiers')
->leftJoin('pointages','pointages.chantier_id','chantiers.id')
->selectRaw('COALESCE(SUM(pointages.sold),0) AS sold, ANY_VALUE(chantiers.chantier) AS chantier, pointages.chantier_id')
->groupBy('pointages.chantier_id')
->get();
PS: ANY_VALUE
does not exist on MariaDB .
Group by only possible on select field
As per your above query, you don't add group by field in the select field that why Laravel gave you the error.
So can you please try following which will work for you
$dataP = DB::table('chantiers')
->leftJoin('pointages','pointages.chantier_id','chantiers.id')
->selectRaw('COALESCE(SUM(pointages.sold),0) as sold,chantiers.chantier,pointages.chantier_id')
->groupBy('pointages.chantier_id')
->get();
Hope you get your require answer
在数据库 sql 中运行此命令
SET GLOBAL sql_mode='';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.