Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
tomduggan85 opened this issue Jul 25, 2018 · 2 comments

Comments

@tomduggan85
Copy link

models.Customers.belongsTo(models.Flights, {

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
Copy link
Collaborator

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?

NouraldinS added a commit that referenced this issue Jul 26, 2018
Fix the database related issues #15 #16 #17
@tomduggan85
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants