Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to use `relationship()` in SQLAlchemy?

I've noticed that many SQLAlchemy tutorials would use relationship() in "connecting" multiple tables together, may their relationship be one-to-one, one-to-many, or many-to-many. However, when using raw SQL, you are not able to define the relationships between tables explicitly, as far as I know.

In what cases is relationship() required and not required? Why do we have to explicitly define the relationship between tables in SQLAlchemy?

like image 319
Sean Francis N. Ballais Avatar asked Sep 28 '17 06:09

Sean Francis N. Ballais


1 Answers

In SQL, tables are related to each other via foreign keys. In an ORM, models are related to each other via relationships. You're not required to use relationships, just as you are not required to use models (i.e. the ORM). Mapped classes give you the ability to work with tables as if they are objects in memory; along the same lines, relationships give you the ability to work with foreign keys as if they are references in memory.

You want to set up relationships for the same purpose as wanting to set up models: convenience. For this reason, the two go hand-in-hand. It is uncommon to see models with raw foreign keys but no relationships.

like image 151
univerio Avatar answered Oct 13 '22 19:10

univerio