In laravel 10/mysql 8 app I have a table with datetime field:
public function up(): void
{
Schema::create('reactions', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->nullable()->references('id')->on('users')->onDelete('CASCADE');
$table->morphs('model');
$table->unsignedTinyInteger('action');
$table->timestamp('created_at')->useCurrent();
$table->unique(['model_type', 'model_id', 'user_id', 'action'], 'reactions_4fields_unique');
$table->index(['model_type', 'model_id', 'action', 'created_at'], 'reactions_4fields_index');
$table->index(['created_at', 'model_type', 'model_id'], 'reactions_3fields_index');
});
}
and running request by date :
$this->reactions = Reaction
::query()->whereDate('created_at', $this->filterAtDate)
->groupBy('action')
->orderBy('reaction_count', 'desc')
->select(
$reactionTb . '.action',
DB::raw('count(' . $reactionTb . '.id) as reaction_count'))
->get()->toArray();
I check explain of the request :
explain SELECT `reactions`.`action`, count(reactions.id) AS reaction_count
FROM `reactions`
WHERE date(`created_at`) = '2024-05-14 00:00:00'
GROUP BY `action`
ORDER BY `reaction_count` desc
and see as created_at is time too “date” method is used and in explain output with
Possible keys:
reactions_4fields_unique,reactions_4fields_index
Key :
reactions_4fields_index
Not sure if indexing of created_at field would work here ? Is whereDate method good here ?
I see decision for latest version for mysql and postgresql…