0
votes

I have a users table that I have associated with an assets table by the user ID. I created the hasMany association from the users table to the assets table and the belongsTo association from the assets table to the users table. When I perform a findAll on the assets table I get the proper user information back based on the associations made. The problem is that the user record has the password hash and other properties coming with it that I done want. I only want the name coming with this association.

I have tried using the attributes tag inside the association but that didn't work.

Model.associate = (models) => {
    Model.belongsTo(models.User, { 
        as: 'user'
    });
}

Model.associate = (models) => {
    Model.hasMany(models.Asset);
}

If I can exclude columns, I would only expect to see the user's first name and last name come back from the users table.

1
The attributes is used on the query, inside the association. Check this for an example. - Ellebkey
Ya i saw that example and figured I was misusing it. I am doing a findAll without passing anything but an include: { all: true }. I was trying to not have to specify it in each query where I reference the user table. Is there a global way to remove it from its associations? - Andrew
@Ellebkey I've tried variations of the below in the association. None work. Model.belongsTo(models.User, { as: 'user', // attributes: { // exclude: [ // 'user.email' // ], // }, attributes: { include: [ 'email' ], }, // attributes: [ // 'user.email' // ], constraints: false }); - Andrew
can you please update your question with the query son I can see better what are you doing. - Ellebkey

1 Answers

0
votes

You can specify attributes like this attributes: ['firstname', 'lastname']

So the query would be something like

const assets = await asset.findAll({
attributes: ['attributes that you want to be included for assets table'],
include: [{
   model: User,
   attributes: ['firstname', 'lastname'],
 }]
})