通过日期时间字段制作过滤器时,whereDate 方法是否好?

问题描述 投票:0回答:1

在 laravel 10/mysql 8 应用程序中,我有一个带有日期时间字段的表:

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');
    });
}

并按日期运行请求:

$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();

我检查请求的解释:

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

看到创建的时间也是“日期”方法,并在解释输出中使用 可能的按键:

reactions_4fields_unique,reactions_4fields_index

关键:

reactions_4fields_index

不确定created_at字段的索引在这里是否有效? whereDate 方法在这里好吗? 我看到了 mysql 和 postgresql 最新版本的决定...

mysql laravel eloquent
1个回答
0
投票

我找到了一个有方法的决定:

::query()->whereBetween('created_at', [$filterAtDate, $filterAtDate->clone()->addDays(1)])

以这种方式进行克隆,我在 sql 跟踪中有 2 个不同的日期

© www.soinside.com 2019 - 2024. All rights reserved.