Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize findAll() with where-parameter returns null while findByPk() returns correct data

I'm setting up resolvers for a GraphQL API right now and running into some problems/questions regarding the findAll() function from sequelize.

I have these 2 resolvers:

User: async (parent, { id }, { models }) => {
  return await models.User.findAll({
    where: {
      ID_User: id
    }
  });
}

UserPK: async (parent, { id }, { models }) => {
  return await models.User.findByPk(id);
}

Models:

type Query {
  UserPK(id: ID): User
  User(id: ID): User
}
type User {
  ID_User: ID,
  Username: String,
}

If I now run these queries

{
 UserPK(id: 1) {
    ID_User
    Username
  }
 User(id: 1) {
    ID_User
    Username
  }
}

Only the UserPK returns (correct) data, the User query returns null for every field which confuses me because the queries sequelize executes are exactly the same.

Executing (default): SELECT `ID_User`, `Username` FROM `User` AS `User` WHERE `User`.`ID_User` = '1';
Executing (default): SELECT `ID_User`, `Username` FROM `User` AS `User` WHERE `User`.`ID_User` = '1';

I'm using apollo server btw if that makes any difference.

like image 785
Mathis Witte Avatar asked Dec 14 '25 18:12

Mathis Witte


1 Answers

The difference between findByPk and findAll is that findByPk returns already a single element whereas findAll returns and array. You don't seem to take that into account. After that the resolvers for User receive an array where they cannot read properties from.

return (await models.User.findAll({
  where: {
    ID_User: id
  }
}))[0];
like image 124
Herku Avatar answered Dec 18 '25 06:12

Herku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!