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

Laravel Eloquent:API用camelCase、数据库用snake_case的简便方案

解决方案:API camelCase 与数据库 snake_case 自动映射

不用手动编写每个属性的设置器/获取器,主流技术栈都有现成的工具或配置方案实现自动命名转换,以下是常见场景的具体实现:

Python 生态

Django + DRF

直接使用djangorestframework-camel-case扩展包,全局配置即可实现API请求/响应与数据库的命名自动转换:

  1. 安装包:
    pip install djangorestframework-camel-case
    
  2. 在项目settings.py中配置DRF的渲染器和解析器:
    REST_FRAMEWORK = {
        'DEFAULT_RENDERER_CLASSES': (
            'djangorestframework_camel_case.render.CamelCaseJSONRenderer',
            'rest_framework.renderers.BrowsableAPIRenderer', # 保留浏览器可查看的渲染器
        ),
        'DEFAULT_PARSER_CLASSES': (
            'djangorestframework_camel_case.parser.CamelCaseJSONParser',
            'rest_framework.parsers.FormParser',
            'rest_framework.parsers.MultiPartParser',
        ),
    }
    
    配置后,数据库字段用snake_case定义,API交互自动使用camelCase,无需修改模型代码。

SQLAlchemy

结合marshmallow和marshmallow-camelcase实现序列化/反序列化的自动转换:

  1. 安装依赖:
    pip install marshmallow marshmallow-camelcase
    
  2. 定义Schema时使用CamelCaseSchema基类:
    from marshmallow_camelcase import CamelCaseSchema
    from marshmallow import fields
    
    class UserSchema(CamelCaseSchema):
        id = fields.Int()
        first_name = fields.Str() # 对应数据库snake_case字段
        last_name = fields.Str()
    
    # 序列化时自动转camelCase
    user_schema = UserSchema()
    serialized_data = user_schema.dump(user_instance)
    
    模型中数据库字段保持snake_case,Schema自动处理命名转换。

Java Spring Boot

利用Jackson的全局配置实现自动映射:

  1. 在application.yml中添加配置:
    spring:
      jackson:
        property-naming-strategy: SNAKE_CASE
    
  2. 实体类中使用camelCase属性名,数据库字段用snake_case,JPA自动映射:
    @Entity
    @Table(name = "user")
    public class User {
        @Id
        private Long id;
        private String firstName; // API返回camelCase,对应数据库first_name字段
        private String lastName;
    
        // 省略getter/setter(可通过Lombok自动生成)
    }
    
    配置后,API请求/响应自动转换为camelCase,数据库交互保持snake_case。

Node.js 生态

TypeORM(含NestJS)

  1. 使用typeorm-naming-strategies设置数据库字段的snake_case命名策略:
    npm install typeorm-naming-strategies
    
  2. 在TypeORM配置中指定命名策略:
    import { SnakeNamingStrategy } from 'typeorm-naming-strategies';
    
    const config: DataSourceOptions = {
        type: 'mysql',
        host: 'localhost',
        // 其他数据库配置
        namingStrategy: new SnakeNamingStrategy(), // 自动将camelCase属性转为snake_case字段
    };
    
  3. 结合class-transformer实现API的camelCase转换(NestJS中可全局配置):
    import { NestFactory } from '@nestjs/core';
    import { AppModule } from './app.module';
    import { ValidationPipe } from '@nestjs/common';
    
    async function bootstrap() {
        const app = await NestFactory.create(AppModule);
        app.useGlobalPipes(new ValidationPipe({
            transform: true,
            transformOptions: {
                enableImplicitConversion: true,
            },
        }));
        await app.listen(3000);
    }
    bootstrap();
    
    实体类用camelCase属性,数据库自动生成snake_case字段,API交互自动转换为camelCase。

Mongoose

使用mongoose-camelcase插件自动处理命名转换:

  1. 安装插件:
    npm install mongoose-camelcase
    
  2. 在Schema中启用插件:
    const mongoose = require('mongoose');
    const camelCase = require('mongoose-camelcase');
    
    const userSchema = new mongoose.Schema({
        first_name: String,
        last_name: String
    });
    
    userSchema.plugin(camelCase); // 自动将snake_case字段转为camelCase属性
    
    const User = mongoose.model('User', userSchema);
    
    查询时返回的文档会自动将snake_case字段转为camelCase属性,API直接返回即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 01:04:58