Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

thinkjs3.0 数据库返回字段只有下划线问题,能否设置映射 #1677

Open
handoudou opened this issue Jul 7, 2021 · 2 comments

Comments

@handoudou
Copy link

DESC

ENV

OS Platform: mac

Node.js Version: v14.15.5

ThinkJS Version: 3.2.10

code

// your code here

error message

// your error message here

more description

// your detail description

#529

@lizheming
Copy link
Contributor

lizheming commented Jul 7, 2021

看了一下,似乎没有支持。不过我觉得你可以使用 afterSelectafterFind 钩子自行实现。类似下面这样

module.exports = class extends think.Model {
  camelize(obj) {
    for(const k in obj) {
      if(!k.includes('_')) {
        continue;
      }
      const newKey = k.replace(/([-_][a-z])/ig, ($1) => {
        return $1.toUpperCase()
          .replace('_', '');
      });
      obj[newKey] = obj[k];
      delete obj[k];
    }
    return obj;
  }

  afterSelect(data) { return data.map(item => this.camelize(item)); }
  afterFind(data) { return this.camelize(data); }
}

@XiaoPuO
Copy link

XiaoPuO commented Jun 25, 2023

看了一下,似乎没有支持。不过我觉得你可以使用 afterSelectafterFind 钩子自行实现。类似下面这样

module.exports = class extends think.Model {
  camelize(obj) {
    for(const k in obj) {
      if(!k.includes('_')) {
        continue;
      }
      const newKey = k.replace(/([-_][a-z])/ig, ($1) => {
        return $1.toUpperCase()
          .replace('_', '');
      });
      obj[newKey] = obj[k];
      delete obj[k];
    }
    return obj;
  }

  afterSelect(data) { return data.map(item => this.camelize(item)); }
  afterFind(data) { return this.camelize(data); }
}
  if (!k.includes('_')) {
    continue; // 使用 continue 不然会出现null
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants