LoopBack 4:如何访问名称含下划线的数据库表
解决LoopBack 4中访问带下划线表名的问题
我之前也碰到过一模一样的情况,这是LoopBack 4默认的命名转换策略在搞鬼——它会自动把下划线分隔的名称转换成驼峰式或连字符格式,导致模型和数据库表的映射不匹配。下面是具体的解决步骤:
1. 显式指定模型对应的数据库表名
当你用lb4 model my_data生成模型时,LoopBack会自动创建MyData类,并默认尝试映射到mydata(去掉下划线)的表,这就是你看到relation public.mydata does not exist错误的核心原因。
解决方法是在模型类的@model装饰器里,手动指定数据库的实际表名:
import {Entity, model, property} from '@loopback/repository'; @model({ settings: { // 根据你的数据库类型选择配置项:PostgreSQL用postgresql.table,MySQL用mysql.table postgresql: { table: 'my_data', // 填写数据库里的真实表名 }, strict: true, // 直接设置为true消除strict模式的警告 }, }) export class MyData extends Entity { // 字段定义... }
2. 处理字段名的映射(可选但推荐)
你的表字段是first_name、last_name这类下划线格式,LoopBack默认会把模型里的驼峰字段(比如firstName)自动转换成下划线列名,但为了更清晰或者避免意外,你有两种选择:
方法A:全局开启下划线转换
在模型的settings里添加underscored: true,让LoopBack自动处理所有字段的命名转换:
@model({ settings: { postgresql: { table: 'my_data', }, strict: true, underscored: true, // 开启后,模型的驼峰字段会自动映射到下划线列名 }, }) export class MyData extends Entity { @property({ type: 'number', id: true, generated: true, }) id?: number; @property({ type: 'string', required: true, }) firstName: string; // 自动对应数据库的first_name列 @property({ type: 'string', required: true, }) lastName: string; // 自动对应数据库的last_name列 constructor(data?: Partial<MyData>) { super(data); } }
方法B:给单个字段显式指定列名
如果不想全局开启,也可以给每个字段单独设置数据库列名:
@property({ type: 'string', required: true, postgresql: { columnName: 'first_name', // 显式指定对应数据库的列名 }, }) firstName: string;
3. 验证修复效果
修改完模型代码后,重启你的LoopBack服务,再调用GET /my_data接口,应该就能正常查询到my_data表的数据了,同时strict模式的警告也会消失。
内容的提问来源于stack exchange,提问作者CoderXT
相关产品推荐
相关产品推荐

