Guest User

Untitled

a guest
Dec 18th, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. var User = db.seq.define('User',{
  2. username: { type: db.Sequelize.STRING},
  3. email: { type: db.Sequelize.STRING},
  4. password: { type: db.Sequelize.STRING},
  5. sex : { type: db.Sequelize.INTEGER},
  6. day_birth: { type: db.Sequelize.INTEGER},
  7. month_birth: { type: db.Sequelize.INTEGER},
  8. year_birth: { type: db.Sequelize.INTEGER}
  9.  
  10. });
  11.  
  12. User.sync().success(function(){
  13. console.log("table created")
  14. }).error(function(error){
  15. console.log(err);
  16. })
  17.  
  18.  
  19. var Post = db.seq.define("Post",{
  20. body: { type: db.Sequelize.TEXT },
  21. user_id: { type: db.Sequelize.INTEGER},
  22. likes: { type: db.Sequelize.INTEGER, defaultValue: 0 },
  23.  
  24. });
  25.  
  26. Post.sync().success(function(){
  27. console.log("table created")
  28. }).error(function(error){
  29. console.log(err);
  30. })
  31.  
  32. db.seq.query('SELECT * FROM posts, users WHERE posts.user_id = users.id ').success(function(rows){
  33. res.json(rows);
  34. });
  35.  
  36. User.hasMany(Post, {foreignKey: 'user_id'})
  37. Post.belongsTo(User, {foreignKey: 'user_id'})
  38.  
  39. Post.find({ where: { ...}, include: [User]})
  40.  
  41. SELECT
  42. `posts`.*,
  43. `users`.`username` AS `users.username`, `users`.`email` AS `users.email`,
  44. `users`.`password` AS `users.password`, `users`.`sex` AS `users.sex`,
  45. `users`.`day_birth` AS `users.day_birth`,
  46. `users`.`month_birth` AS `users.month_birth`,
  47. `users`.`year_birth` AS `users.year_birth`, `users`.`id` AS `users.id`,
  48. `users`.`createdAt` AS `users.createdAt`,
  49. `users`.`updatedAt` AS `users.updatedAt`
  50. FROM `posts`
  51. LEFT OUTER JOIN `users` AS `users` ON `users`.`id` = `posts`.`user_id`;
  52.  
  53. Model1.belongsTo(Model2, { as: 'alias' })
  54.  
  55. Model1.findAll({include: [{model: Model2 , as: 'alias' }]},{raw: true}).success(onSuccess).error(onError);
Add Comment
Please, Sign In to add comment