I want to group by table by name and select name and date, for name with same values have deferent valus of date, I tried this but don't work :
public function period(Request $req)
{
$absences = Absence::whereBetween('date', [$req->from, $req->to])->get();
$daily = $absences->select('name ','date', 'COUNT(date) as counts');
$arr['absences'] = $absences;
$arr['daily'] = $daily;
$arr['from'] = $req->from;
$arr['to'] = $req->to;
return $arr;
return view('period',$arr,);
}
I get error : Method Illuminate\Database\Eloquent\Collection::select does not exist.
and when I used this :
public function period(Request $req)
{
$absences = Absence::selectraw('name , date')->whereBetween('date', [$req->from, $req->to])->groupBy('name')->get();
$arr['absences'] = $absences;
$arr['from'] = $req->from;
$arr['to'] = $req->to;
//return $arr;
return view('period',$arr,);
}
I get this :
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'absences.absences.date' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select name , date from
absences
wheredate
between 2021-10-02 and 2021-10-12 group byname
)
CodePudding user response:
Can you try this? I think the issue is you forgot to group by your selected (non-aggregate) columns.
$daily = Absence::query()
->select('name', 'date')
->selectRaw('count(date) as counts')
->whereBetween('date', [$req->from, $req->to])
->groupBy('name', 'date')
->get();
dd($daily);
CodePudding user response:
all column in select clause should be in gorup by too, this is the strict mode in mysql. if you want to change it, go to config/database.php and set it to false:
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'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', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => false, // instead of true
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],