FACG4 / nigerian-airlines

MIT License
0 stars 1 forks source link

Set up customer -> flight relation to allow flights to have many customers #17

Open tomduggan85 opened 6 years ago

tomduggan85 commented 6 years ago

https://github.com/FACG4/nigerian-airlines/blob/bb60785ca1a4ea3d7b8a50f0d9ef8c643df6965f/server/database/models/index.js#L10

Right now, the relation between customer and flight is a one-to-one relation (using belongsTo). I think that the app could support having multiple customers per flight, which would mean that this relation has to change to a one-to-many relation.

Here's the sequelize docs on one-to-many relations: http://docs.sequelizejs.com/manual/tutorial/associations.html#one-to-many-associations-hasmany-

The simplest way would be to use hasMany, to connect one source (here, the Flight) to multiple targets (Customers): models.Flights.hasMany(models.Customers)

amusameh commented 6 years ago

Edited, thanks. I have a question though, I know I should follow the docs but I did define the tables using belongsTo before and it worked same way as hasMany, and I also saw some answers online that used both relations at the same time

models.Flights.hasMany(models.Customers)
models.Customers.belongsTo(models.Flights)

https://stackoverflow.com/questions/20290815/belongsto-vs-hasmany-in-sequelize-js

So I wonder what is the exact different between these cases?

tomduggan85 commented 6 years ago

Ah yeah, I see what you're saying - that can be confusing.

If you have models.Flights.hasMany(models.Customers), or models.Customers.belongsTo(models.Flights), or both, they all do the same thing to the underlying tables: add a flights_id foreign key to the Customers table which points to rows in the Flights table.

The difference is in how you can use the model instances. If you set up the hasMany relation on Flights, then you can easily get all customers for a flight model using the built-in functions that sequelize adds (myFlight.getCustomers()), which will be useful when you build the API that notifies all customers when updating the flight. If you don't have the hasMany relation, then you don't have that easy way of getting all customers for a flight.
.. and the same for Customers.belongsTo: if you create that relation, then you have customer.getFlight() available to you.