Advanced Database Relationships

As we saw in the Designing your Database section, databases can have weird cases. Specifically, we saw what's called a foreign Key Relationship.

Foreign Key

Keeping to our example, we can use Posts and Likes as an example of a Foreign Key relationship. Specifically, what's happening here is that for every one (1) Post, there can be several (n) Likes, so there is a 1 to n relationship. Whenever there is a 1 to n relationship, we say there is a Foreign Key relationship. Specifically, we say that the n has a Foreign Key to the 1.

So in our case with the Posts and Likes, we say that the Likes have a foreign key to the Posts. Also, if you look at the code we've written, you'll see we also only keep track of the foreign key on the side of the Likes.

Many to Many

Foreign key relationships represent 1 to n relationships whereas Many-to-many relationships represent n to m relationships.

One good example of this is Students and Classes. For example, I'm in five classes, so I as 1 student am enrolled in many classes. Each of my classes has 30 students, so each of my classes has many students.

One student can have many classes and one class can have many students -- many-to-many.

One to One

Same Idea here but instead of 1 to n or n to m, we're talking 1 to 1.

results matching ""

    No results matching ""