If a primary key is a unique identifier for a record within a table, then a foreign key is a reference to a primary key on a foreign table.
A constraint allows you to protect the integrity of your database tables. Imagine an order that is associated with a customer who no longer exists in your system. Luckily, we can guard ourselves against such orphans.
Now that you understand keys a bit more, let's switch over to a fresh Laravel app and review how we can represent these relationships and constraints through Laravel migrations.
If the various MySQL join types confuse you, don't worry: you're not the only one. Inner Join, Outer Join, Left Join, Right Join...what the heck? But, as it turns out, once you understand the basic structure of a join, everything else should quickly fall into place. In this episode, we'll review everything you need to know.
An excellent way to learn MySQL is to ask yourself: "If this was my domain, what sorts of questions might I ask?" One such question might be, "How many movies has each user rented?" To calculate numbers like this, we'll leverage MySQL aggregate functions and the
GROUP BY clause.
If necessary, you can join any number of tables as part of your
SELECT statement. In this episode, we'll add a second
LEFT JOIN clause to the query we wrote in the previous episode. This will also give us the opportunity to discuss subqueries.
Here's another question we might ask: "Which movies have been the most profitable?" Once we solve this riddle, we can then answer a second question based on that information: "Of those results, which movies have made at least $200?"
A "one-to-one" database relationship is incredibly simple to understand. If you can say that a single record from one table is related to a single record from another table, in both directions, then you have a one-to-one relationship. Here are a few examples to get you started: "A person has one social security number." "A subscriber has one profile." "A manager has one team."
A one-to-many relationship is the second easiest to understand. A user may have many posts. A post may have many comments. A team may have many members. In each of these examples, a single record is related to any number of related records from a related table.
*Series still in development. Check back often for updates.