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

Adonisjs中如何配置模型将布尔字段返回的0/1转换为true/false

解决方案

Adonis框架的Lucid ORM内置了字段类型自动转换能力,你只需要在Markup模型中添加casts静态配置即可实现open字段的自动布尔转换,不需要修改数据库或其他全局配置。

修改步骤

  1. 打开你的Markup模型文件,在类中添加casts静态getter,指定open字段的转换类型为boolean,修改后的完整模型代码如下:
const Model = use('Model')

class Markup extends Model {
  static boot() {
    super.boot()
    this.addTrait('@provider:Lucid/SoftDeletes')
  }

  // 新增字段转换配置
  static get casts() {
    return {
      open: 'boolean'
    }
  }

  static getColumns() {
    return ['assignee_id', 'editor_details', 'visibility', 'image_url', 'priority', 'open']
  }

  comments() {
    return this.hasMany('App/Models/Comment', 'id', 'markup_id')
  }

  assignee() {
    return this.belongsTo("App/Models/User", "assignee_id", "id")
  }

  created_by() {
    return this.belongsTo("App/Models/User", 'created_by_id', 'id')
  }

  resolved_by() {
    return this.belongsTo("App/Models/User", 'resolved_by_id', 'id')
  }
}

module.exports = Markup

规则说明

  • 该配置会在读取数据时自动把MySQL返回的0/1数值转换为false/true布尔值,写入数据时也会自动把传入的布尔值转换为对应1/0存入数据库,不需要额外手动处理
  • 如果你有多个需要转换的布尔字段,直接在casts对象中追加键值对即可,例如is_active: 'boolean'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 22:45:03