title: Sequelize one to many query
body: <p>Hello I am trying to make a query between a one to many table (one user has many preferences). At the moment, I have a query that consist of a search for the ID of the user in the User table and a search in the preferences table for that ID. This is my working solution.</p>
  
  <pre><code>        const {username} = req.params
  
          User.findOne({where: {username: username}, attributes:['id']})
              .then(res =&gt; {
                  const obj = res.get({plain:true})
                  Preferences.findAll({ where:{ userId: obj.id}})
                      .then(res =&gt; {
                          const data = res.map((r) =&gt; (r.toJSON()));
                          console.log('sucess: ', data)
                      })
                      .catch(err =&gt; console.log('inner error'))
              .catch(err =&gt; console.log('outer error', err))
              })
  </code></pre>
  
  <p>How can I refine this with a .findAll query? I've come up with the following query which returns all the users with a foreign key in the Preferences table. However, I can't get this to work for a specific username. </p>
  
  <pre><code>        Preferences.findAll({
              include: [{
                  model: User, 
                  where: {userId: sequelize.where(Sequelize.col('userId'), Sequelize.col('User.id'))}
              }]
          })
  </code></pre>
  
  <p>If this question has already been answered can you kindly direct me to the post? I've been digging through Stack Overflow solutions but haven't had any luck. Thanks in advance!</p>
  
  <p>//============================</p>
  
  <p>Here's the final solution in case it helps anyone in the future. I fixed the association between my models and tweaked the query:</p>
  
  <pre><code>//User has many Preferences 
  User.hasMany(models.Preferences, {
    foreignKey: 'userId', 
    sourceKey: 'id',
  });
  
  //Preferences has one User
  Preferences.belongsTo(models.User,{
    foreignKey: 'userId', 
    targetKey: 'id',
    onDelete: 'CASCADE',
  });
  
  
  //Query for Preferences by Username
  
  get: (req, res) =&gt; {
      const {username} = req.params
      User.findAll({
        include: [{
          model: Preferences, 
          }],
          where: {username: username}
      })
      .then(response =&gt; {
          const data = response.map((r) =&gt; (r.toJSON()));
          console.log('success: ', data[0].Preferences)   
      })
      .catch(err =&gt; console.log('outer error', err))
  }
  </code></pre>