0

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.

4
  • The attributes is used on the query, inside the association. Check this for an example. Commented Apr 9, 2019 at 16:54
  • 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? Commented Apr 9, 2019 at 17:48
  • @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 }); Commented Apr 9, 2019 at 18:03
  • can you please update your question with the query son I can see better what are you doing. Commented Apr 10, 2019 at 14:39

1 Answer 1

1

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'], }] }) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.