Possible to use one model on clones of a table?

701 views
Skip to first unread message

Andrew Eddie

unread,
Jan 13, 2016, 2:40:54 AM1/13/16
to Sequelize
I'm trying to work out a way to use a single model to "shard" data that I'm importing from different customers' business systems. For example, let's say I'm pulling down basic employee information where my schema might be something like:

guid: string  // A GUID that I generate to link with other tables
name: string  // The name of the employee
login: string // Their login on their corporate system

Now it's trivial to create a model and a table to store that, but let's say I need to keep my different customers completely separate (I could use a customerId field in the table, but I don't want any risk of data collision), so my database names might look like:

company1_guid_login_map
company2_guid_login_map

Where each table is just a clone of the original model.

Is there any way I can create just one Sequelize model where I can dynamically change the table name depending on what customer's information I'm working on?

Thanks in advance.

Regards,
Andrew Eddie

Mick Hansen

unread,
Jan 13, 2016, 2:44:11 AM1/13/16
to Andrew Eddie, Sequelize
There's nothing built in at the moment, but you could probably get something to work.
We don't currently expose a Model.clone() method but one could likely be extracted from: https://github.com/sequelize/sequelize/blob/master/lib/model.js#L1031
You could then modify Model.options.tableName as you see fit (although not public API) or overload Model.getTableName() possibly.
--
Mick Hansen
@mhansendev
mhansen.io

Marcos Polanco

unread,
Jun 9, 2018, 10:14:38 PM6/9/18
to Sequelize
I am now looking at this exact same situation. Is the response unchanged? Thx!

Pete Gaffney

unread,
Jul 19, 2018, 7:21:11 PM7/19/18
to Sequelize
I think you would usually do this using one table and one model, then only expose the model through a service or functional interface that requires a customerId.

If you want to do it this way, I would think you'd make three models using a sequelize.define statement that is mostly built out of common code included from a shared file.  You could maybe put those in an object and access the model you want using a customer identifier.  This way, you'd end up with an object like this:

const customersModel = {
  company1: company1model,
  company2: company2model,
  company3: company3model
}

and you'd call it something like this:

let companyIWant = "company1"
customersModel[companyIWant].get(params)

Reply all
Reply to author
Forward
0 new messages