###Goal
- Building a simple schema with many-to-many relationship
- Write to the database with 3NF
- Read from database through join table
See the presentation slide deck here
- Nodal v0.10.0
- Postgres
- Postman
nodal s
Nodal should now be running on localhost:3000.
Generated by Nodal
- The master branch has the basic nodal skeleton set up
- Models and controllers have been generated for User and Group table
- The sulution branch has the model and controller for User_Group table
- An end point is set up for writing to User_Group table with foreign key
- An end point is set up for getting group names that a user belongs to
- Create user_group table to join user and group
nodal g:model user_group user_id:int group_id:int
nodal g:controller v1 --for user_group
- Create a database in postgres and create blank tables
nodal db:create
nodal db:prepare
nodal db:migrate
- seeding the database with dummy data
nodal db:seed
nodal db:bootstrap
- https://localhost:3000/v1/users
- https://localhost:3000/v1/groups
- https://localhost:3000/v1/user_groups
- Modify the
user_groups_controller.js
const User = Nodal.require('app/models/user.js');
const Group = Nodal.require('app/models/group.js');
//....
create() {
let user_id;
let group_id;
let user_group;
const userName = { name: this.params.body.userName };
const groupName = { name: this.params.body.groupName };
User.findOrCreateBy("name", userName, (err, user) => {
if ( err ) { return this.respond(err); } // make sure your handle error
user_id = user.get('id');
Group.findOrCreateBy("name", groupName, (err, group) => {
if ( err ) { return this.respond(err); } // every step!!!
group_id = group.get('id');
user_group = { user_id, group_id };
UserGroup.create(user_group, (err, userGroup) => {
this.respond(err || userGroup);
});
});
});
$ psql -U postgres
$ \l
$ \c nodal_schema_development
$ \dt
$ SELECT * FROM users;
- Modify the
user.js
model
Group.joinsBy(UserGroup, {multiple: true});
- Modify the
group.js
model
Group.joinsBy(UserGroup, {multiple: true});
- Modify the
user_group.js
model
UserGroup.joinsTo(User, {multiple: true});
UserGroup.joinsTo(Group, {multiple: true});
- Modify the 'users_controller'
UserGroup.query()
.join('user')
.join('group')
.where(this.params.query)
.end((err, models) => {
this.respond(err || models, [{'user': ['id', 'name']}, {'group': ['id', 'name']}]);
});