You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel如何编写兼容MySQL与SQLite的大小写不敏感唯一列迁移

#Laravel 8 兼容MySQL、SQLite的大小写不敏感唯一用户名字段实现方案

核心实现思路

通过构建基于username字段小写值的函数索引,让两种数据库的唯一约束统一校验小写后的内容,天然实现大小写不敏感的校验逻辑,不需要编写数据库专属的原生SQL,也不需要依赖仅部分数据库支持的collation修饰符。

调整后的迁移代码

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('username')->nullable();
            // 声明基于小写username的唯一索引,跨数据库自动适配大小写不敏感校验
            $table->unique(DB::raw('LOWER(username)'), 'users_username_unique');
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
};

可选优化(推荐配合使用)

为了简化后续查询逻辑,不需要每次查询都手动包裹LOWER()函数,可以在User模型中添加修改器,统一将username转为小写后存入数据库:

//  App\Models\User.php
public function setUsernameAttribute($value)
{
    $this->attributes['username'] = strtolower($value);
}

方案说明

  • 该实现对MySQL和SQLite完全兼容,无需分驱动写分支逻辑
  • 唯一约束会自动将提交的username转为小写后比对,MAX和max会被判定为重复值,完全符合需求
  • 仅在索引声明时用DB::raw包裹SQL函数,没有编写整段原生建库语句,符合Laravel迁移的语法规范

内容的提问来源于stack exchange,提问作者Adam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 15:18:04