【问题标题】:How to create a joint column in mysql off of a calculation of other columns如何在 mysql 中根据其他列的计算创建一个联合列
【发布时间】:2017-09-18 16:46:41
【问题描述】:

我正在尝试在我的用户模型中创建一个“总列”。我不确定如何进行计算。以前我在前端执行此操作,但这使我的排序选项非常有限,因此我想在后端执行此操作,然后追加总行。

这是我的模型的样子: 模块.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
}

但这似乎不起作用,有什么想法可以从我的用户模型中做到这一点吗?

【问题讨论】:

    标签: mysql database model sails.js


    【解决方案1】:

    我认为做你想做的唯一方法是将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 调用时执行此操作等。

    【讨论】:

    • 感谢您的回答,我在前端计算它,就在我附加分数的地方,但它让排序有点让人头疼。听起来这可能是实现它的理想方式,但感谢您的帮助!
    • 是的,我明白了 - 如果您获得大量用户,您不想获得所有记录,而只想获得百分比最高的那些。在这种情况下,这个afterUpdate 可能真的是你需要的。
    • 幸好我只需要拉32,我可以根据胜数排序
    【解决方案2】:

    查看文档,也许这会起作用

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

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

    【讨论】:

    • 所以当我添加它时,当我尝试登录应用程序时,我会收到[Error (E_UNKNOWN) Encountered an unexpected error] Details: Error: ER_BAD_FIELD_ERROR: Unknown column 'user.scorepct' in 'field list'。但是,如果我将该列也添加到我的表中,它将导致null。 ://
    • ofc,我忘了return >
    • 嗯,仍然为我返回“null”。我认为这是在正确的轨道上。
    猜你喜欢
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2021-03-20
    相关资源
    最近更新 更多