简体   繁体   English

Node.js将JOIN用于序列表上的两个表

[英]Nodejs use JOIN for two tables on sequelize

I'm trying to implementing this mysql command on sequelize, but as far as i'm newbie to use this library i can't implementing that 我正在尝试在sequelize上实现此mysql命令,但就我是使用该库的新手而言,我无法实现该功能

i want to make this sql command: 我想做这个SQL命令:

SELECT * FROM users 
join users_contacts_lists on users_contacts_lists.mobile_number = users.mobile_number 
WHERE users_contacts_lists.user_id = 1

My models to create database schema: 我创建数据库模式的模型:

'use strict';
var config = require('../config');

var User = config.sequelize.define('users', {
    id: {
        type: config.Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    password: {
        type: config.Sequelize.STRING
    },
    username: {
        type: config.Sequelize.STRING
    },
    mobileNumber: {
        type: config.Sequelize.STRING,
        field: 'mobile_number'
    },
    status: {
        type: config.Sequelize.STRING
    },
}, {freezeTableName: true});

var UsersContactsLists = config.sequelize.define('users_contacts_lists', {
    id: {
        type: config.Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    userId: {
        type: config.Sequelize.INTEGER,
        field: 'user_id'
    },
    mobileNumber: {
        type: config.Sequelize.STRING,
        field: 'mobile_number', defaultValue: 0
    }
}, {freezeTableName: true});

UsersContactsLists.belongsTo(ChannelsTypes, {foreignKey: 'user_id'});
User.hasMany(Channels, {foreignKey: 'id'});

User.sync();
UsersContactsLists.sync();

module.exports =
{
    users: User,
    usersContactsLists: UsersContactsLists
};

how can i resolve this problem? 我该如何解决这个问题? Thanks in advance 提前致谢

you can define the target key and the foreign key both in a relation like this : 您可以在这样的关系中定义目标键和外键:

User.belongsTo(UsersContactsLists, {targetKey:'mobileNumber',foreignKey: 'mobileNumber'});

then you can use this : 那么你可以使用这个:

User.findAll({
include: [{
    model: UsersContactsLists,
    where: {
        userId: 1
    }
}]

Fiddled around a bit, does this statement do what you want? 摆弄了一下,这条语句是否可以满足您的要求?

User.findAll({
    include: [{
        model: UsersContactsLists,
        where: {
            userId: 1
        }
    }]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM