Advertisement
Guest User

Untitled

a guest
Jan 25th, 2015
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. "use strict";
  2.  
  3. const Schema = require('schema');
  4. const Migration = require('migration');
  5.  
  6. // Migration builder
  7. let CreateUsersTable = Object.create(Migration);
  8.  
  9. CreateUsersTable.prototype.up = function up() {
  10.  
  11. // Schema takes in a table name and instantiates a table
  12. // for us then to use to chain properties to
  13. Schema.create('tableName', function (table) {
  14. table.increments('id');
  15. table.string('stringField', { length: 500, unique: true });
  16. table.integer('intField');
  17. table.boolean('boolField');
  18. table.date('dateField');
  19. table.timestamps();
  20. });
  21.  
  22. };
  23.  
  24. CreateUsersTable.prototype.down = function down() {
  25. Schema.drop('tableName');
  26. };
  27.  
  28. // Seeder
  29. let UsersTableSeeder = Object.create(Seeder, { table: 'users' });
  30.  
  31. // Run should give us a table object to work with
  32. UsersTableSeeder.prototype.run = function run() {
  33.  
  34. // Delete everything in table
  35. this.table.truncate();
  36.  
  37. let data = [];
  38.  
  39. // Insert data
  40. this.table.seed(data);
  41. }
  42.  
  43. // Eloquent User Model
  44. const Eloquent = require('eloquent');
  45.  
  46. let User = Object.create(Eloquent, { table: 'users' });
  47.  
  48. // Many-to-one relationship
  49. User.prototype.posts = function posts() {
  50. return this.hasMany('post');
  51. }
  52.  
  53. // Many-to-many relationship
  54. User.prototype.groups = function groups() {
  55. return this.belongsToMany('groups');
  56. }
  57.  
  58. // Usage
  59. const User = require('./models/user');
  60.  
  61. let info = { username: 'foo', password: 'bar', email: 'foobar' };
  62.  
  63. User.create(info).then(function (success) {
  64. console.log('User created');
  65. });
  66.  
  67. User.all().then(function (users) { console.log('All users!') });
  68.  
  69. User.find({ id: 3 }).then(function (user) {
  70. console.log('We\'ve found a match for the ${user}');
  71. });
  72.  
  73. User.where({ email: 'foobar' }).then(function (user) {
  74. console.log('Found the user');
  75. });
  76.  
  77. User.destroy({ id: 3 }).then(function (msg) {
  78. console.log('User deleted')
  79. });
  80.  
  81. User.where({ email: 'foobar' }).then(function (user) {
  82.  
  83. });
  84.  
  85. // Relationships
  86. User.find({ id: 3 }).then(function (user) {
  87. console.log('Posts are here: ${user.posts}');
  88.  
  89. // Can subquery further...
  90. return user.posts.where('length', '>', 200);
  91. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement