如何根据其他列的计算在 mysql 中创建联合列

How to create a joint column in mysql off of a calculation of other columns

我正在尝试在我的用户模型中创建一个 'total column'。我不确定如何进行计算。以前我是在前端做的,但这给我留下了非常有限的排序选项,所以我想在后端做这个,然后附加总行。

这是我的模型的样子: module.exports = {

autosubscribe: ['destroy'],

attributes: {
    name: {
        type: 'string',
        required: true
    },
    email: {
        type: 'email',
        unique: true,
        required: true
    },
    password: {
        type: 'string',
        required: true,
        minLength: 6
    },
    status: {
        type: 'string',
        defaultsTo: 'offline',
        required: false
    },
    score: {
        type: 'integer',
        defaultsTo: 0,
        required: false
    },
    totalwins: {
        type: 'integer',
        defaultsTo: 0,
        required: false
    },
    totalgames: {
        type: 'integer',
        defaultsTo: 0,
        required: false
    },
    ip: {
        type: 'string',
        required: false
    }
}
};

我尝试添加类似

的内容
scorepct: {
type: 'integer',
defaultsTo: totalwins/totalgames,
required: false
}

但这似乎不起作用,关于如何从我的用户模型执行此操作有什么想法吗?

查看文档,也许这行得通

scorepct: {
    type: 'integer'
    defaultsTo: function(){ return this.totalwins / this.totalgames }
    required: false
}

scorepct: function(){ return this.totalwins / this.totalgames }

我认为唯一的方法就是将 lifecycle callbacks 添加到您的模型中。您可以确保每次使用默认的 createupdate 方法时,属性 都会按您的意愿更新:

attributes: {
    // ...
    scorepct: {
        type: 'integer'
        defaultsTo: 0 // always 0 at creation time
    },
},

afterUpdate: function(attrs, next) {
    var calculatedPct = attrs.totalgames === 0 ? 0 : attrs.totalwins / attrs.totalgames;
    if (calculatedPct === attrs.scorepct) {
        return next();
    }
    User.update(attrs.id, {scorepct: calculatedPct}).exec(function(err, user) {
        // handle the error
        return next();
    });
},

这似乎很麻烦 - 为什么不在需要的地方计算百分比而不将结果存储在数据库中呢?您可以安排在每个 .find 时自动执行此操作,或者在 api 调用数据等时执行此操作