sequelize关系不适用于char键,但适用于int键

时间:2018-08-05 07:18:59

标签: mysql node.js express twitter sequelize.js

我正在使用expressjs处理续集
我为数据库做了一些模型

'use strict';
module.exports = (sequelize, DataTypes) => {
    var Tweet = sequelize.define('Tweet', {
        twitter: DataTypes.INTEGER(10),
        user_tweet_id: DataTypes.INTEGER(10),
             });
Tweet.associate = function (models) {
    models.Tweet.hasOne(models.User, {
        foreignKey: 'twitter_id', targetKey: 'user_tweet_id', as: "user"
    });
};
return Tweet;
};

用户模型

    module.exports = (sequelize, DataTypes) => {
    var User = sequelize.define('User', {
        username: DataTypes.CHAR(15),
        twitter_id: DataTypes.INTEGER(10),
    }, {
    });

    User.associate = function (models) {
        models.User.hasMany(models.user_relation, {
            foreignKey: 'user_destination_id',
            targetKey: 'twitter_id',
            as: "followers"
        });
     };
    return User;
};

一切都很好,但是我然后我明白了我隐性的ID要大得多10位数字,应该更大,但是因为js只有双精度,所以我应该使用char数组
所以我将其名称和数据类型更改为CHAR(64)

新用户模型

'use strict';
module.exports = (sequelize, DataTypes) => {
    var User = sequelize.define('User', {
        username: DataTypes.CHAR(15),
        remote_user_id: DataTypes.CHAR(64),
    }, );
    User.associate = function (models) {
        models.User.hasMany(models.user_relation, {
            foreignKey: 'user_destination_id',
            targetKey: 'remote_user_id',
            as: "followers"
        });

    };
    return User;
};

我还对tweet模型进行了必要的更改

但我不再工作

  "id": 7,
    "username": "*****",
    "remote_user_id": "1020673370239750144",
    "followers": [],

当我看起来连续记录时,我发现查询它正在运行

   SELECT `User`.`id`, `User`.`username`, `User`.`remote_user_id`,`followers`.`id` AS `followers.id`, `followers`.`user_source_id` AS `followers.user_source_id`, `followers`.`user_destination_id` AS `followers.user_destination_id`  FROM `Users` AS `User` LEFT OUTER JOIN `user_relations` AS `followers` ON `User`.`id` = `followers`.`user_destination_id` 

但我希望查询为

   SELECT `User`.`id`, `User`.`username`, `User`.`remote_user_id`,`followers`.`id` AS `followers.id`, `followers`.`user_source_id` AS `followers.user_source_id`, `followers`.`user_destination_id` AS `followers.user_destination_id`  FROM `Users` AS `User` LEFT OUTER JOIN `user_relations` AS `followers` ON `User`.`remote_user_id` = `followers`.`user_destination_id` 

一切正常

所以我发现sequelize导致其他键错误id而不是user_remote_id

我对targetKey没问题,但是在Integer上很好用

0 个答案:

没有答案