I'm exploring the fields of SQL and relational databases since I'm relatively new to database design and I was wondering about how table/object relationships work. By relationships I mean referencing an id on another table, which is heavily used in frameworks like Laravel with it's ORM Eloquent. In the Documents it's stated how to create relationships, but not WHY and WHEN? What are the benefits or the drawbacks of not doing it?
So my question; When and why do we need to create relationships between tables?
Example:
I was practicing on a Laravel Application for our local indoor Football/Soccer Club which uses multiple tables (and what made me confused about the concept). The tables/resources of my app are:
Competitions
Teams
Matches
Locations
To clear up: There are 7 competitions of 12 teams (so total 84 teams total) who play matches at 3 indoor courts. The matches of every competition are not tied to 1 court, so competition 2B has matches at court 1 and 2 par example.
The target of my app is to show the program/schedule, fixtures and rankings of the different competitions. I want to use relationships so I can retrieve all matches played at court 1 or all matches of competition 2A.
I presumed the relations to be like this:
1. Competitions -> hasMany Teams, | Teams -> belongTo Competition
2. Competitions -> hasMany Matches | Matches -> belongTo Competition
3. Location -> hasMany Matches | Matches -> belongTo Location
4. Matches -> hasMany Teams | Teams -> HaveMany Teams
I created the migrations and the models but I bump into error after error. For example every match has two teams, how to specify this relation? And matches, they belong to a competition and as well to a Location so I can query both locations with all their matches and competitions with all their matches.
Is this all even possible or does evert table can only have one parent/child relation?
Maybe someone has some good resources on this matter for beginner to novice for me to learn and grasp the basics of this matter.
Thanks in advance!
i'm going to try to give you a quick answer.
Basically you create relationships between your models because they are part of their definitions.
WHY ? Because it helps in many cases.
If we take your first relationShip :
1. Competitions -> hasMany Teams, | Teams -> belongTo Competition
Defining that relationship will ease the following operations :
Define the teams which are part of a competition.
$competition->teams()->save($newTeam);
Retrieve the teams which are part of a competition.
$teams = $competition->teams();
Retrieve the competitions which are played by a certain team.
$competitions = $team->competitions();
as those kinds of operations are very common Eloquent ORM allows you to use his simple and efficient syntax instead of writing sometimes complex SQL requests.
WHEN ? Anytime those kinds of relations exists between your models, declare them, always.
Related
Let's say my company is producing medical products, these products are used in many different lab testing instruments. The business logic hierarchy goes like this:
A lab has multiple locations (Up to thousands)
A location has multiple departments (Chemistry, Hematology, 3-5 per location)
A department has multiple instruments (No more than 10-20 instruments per location)
An instrument has many products.(No more than 1-5 product types per instrument)
The table structure currently mirrors the business logic, like displayed on the left. I suggested we make a small change, displayed on the right.
What are some pros and cons of each approach? I feel like the left-hand side approach might be a bit slower due to chaining so many Joins in a row.
The biggest "con" I see to the approach on the right-hand side is that you lose the association between Department and Location. For the relationships that you described atop your post, the structure on the left is correct from a design perspective.
HOWEVER...
The design that you have means that the Mass Spectrometer at your San Antonio facility will have a different ID than the one at your Denver facility. Is that intended?
------------------ revision after discussion in comments ------------------
You've described a couple of many-to-many relationships - a location will have multiple instruments and multiple locations can have the same instrument (e.g. Mass Spectrometer). To support that, you'll need cross-reference tables. Here's an initial sketch. My standard is to call the table's primary key "ID", and any field called "[table-name]_ID" is a foreign key to the corresponding table:
Lab
ID
Name
Location
ID
Lab_ID
Street_Address
City
etc.
Department
ID
Name
Location_Department -- this lists the departments at a given location
ID
Department_ID
Location_ID
Instrument -- Scale, Oscilloscope, Mass Spectrometer, etc.
ID
Name
Description
Location_Department_Instrument -- inventory at a given location
Location_Department_ID
Instrument_ID
Instrument_Serial_Number
Let me know if this makes sense.
I am creating a database for universities in my country. Particular database of name of the courses offered by each university.
I think I must consider the following points to create a database
Possible names of courses, let's assume 100 courses.
Name of courses offered by one university, let's assume 60.
Number of courses offered by university may differ from one university to another. One may offer 60 courses and other may offer just 50. Courses may overlap.
How do I create a relational database between table of point no.1 and table of point no.2, considering the point no.3. Please suggest a design pattern for this.
Normally, you would have a table listing all the available courses (in all universities) and another table including the university and the course (one record for each combination) using the ID of the course from the first table. This, of course, is just a very basic description. You may also wish to have a table for universities, course instances (meaning, the same course may run several times during the year, even overlapping within the same university to cope with high number of students), etc.
You could have:
university_course, which is a type of course at a university
a course_category that broadly collects each type of course together
Many course rows, which give the names of a course within a category.
So:
university_course.university_id -> university.id (a university has many university courses)
university_course.category_id -> category.id (a university course has one category)
course.category_id -> category.id (a category has many courses)
Thus, the set of courses (Computer Science, Networking, Computer Studies, Computer Hardware) can map to a category (Computer Science) and then each university course points to the category.
Usually in self realtionship tutorials it is taught in a subordinative way. Eg.: employee X subordinated to employee Y.
I have this scenario bellow where the related players are actually the same person but with different accounts.
So I don't know whether this is right to use self relationship in this case.
(aka: also known as)
aka_id ----> id_player
One player account is not subordinated to another. Players can have multiple accounts but I'm willing to relate them so I can tell they belong to the same person. In the real scenario, there is no master account to relate them to. this is a NON-SUBURDINATIVE scenario.
I thought of not using relationship in this case and insert a random hash key tag to the aka column:
380 | player120 | ae65a3f01a
500 | player430 | ae65a3f01a
The question here is:
Is it right to use self relationships in non-subordinative scenarios?
From the way you describe the problem, you have two entities: players and aka (which I will call nicknames). These are two separate entities, and that usually suggests three tables:
Players
Nicknames
PlayerNicknames
The third table is a junction table that combines the first two. You might be able to put all the information you need about Nicknames in PlayerNicknames -- that is fine. However, if you have a requirement that all nick names be unique, then you definitely want a third table.
My guess is that you have a player name that is automatically a nick name. Great. When you create a player, also create an entry in the nicknames.
I am building a database on Access that, among other things, tracks who has referred patients to our office (I work in an optometrist's office which does a specialized kind of therapy).
I don't have much experience creating relational databases, and I am wondering if I'm heading the right direction. Before posting here, I've asked 5 of my computer programmer friends for help, but suddenly every is busy... So here goes.
1 patient can have Many referrals
my son's teacher and my coworker referred me here (2 referring
sources)
my doctor told me about you, and then I saw your website (2 referring
sources)
1 referral can consist of:
an individual (Dr Blah-Blah, or My Friend Jane Doe)
an organization (Doctors Group)
an individual that is part of an organization (Dr. So-and-So from Doctors
Group)
a media source (website, pamphlet, commercial, tv show, etc)
Often it's not possible to determine which individual at an organization referred the patient (because patients can't remember), so only the organization is recorded. But sometimes it is possible, so the individual and the organization are recorded. And sometimes individuals are not part of any organization.
This is the partial design that I came up with: http://postimg.org/image/uipaq7rrl/
Patients Table
Referring Media Table
stores details of media sources
Referring Organization Table
stores the names/details of organizations
Referring Individuals Table
stores names/details of individuals
uses Ref Org ID as a foreign key, in case individuals are members of an organization
Referrals Table
uses the Patient ID as a foreign key to link the referrals to the patients
How should I link the Referrals Table to the Ref Org, Ref Indv, and Ref Media tables?
I came up with something like this: http://postimg.org/image/qtpoiflmv/
But that seems redundant and leaves a lot of blank spaces, depending on the type of referral: http://postimg.org/image/oepj99ohz/
What should I do? What is a good way to build relationships between these tables?
without even thinking or getting involved, if you see spaces like that, looks like you need a table with referral types
Can anyone help me to design database/table based on below criteria?
An e-commerce website is required which will allow visitors to browse, search and buy films. The following business logic applies:
Each film can be available in DVD or Blu-ray formats with different stock codes and prices. Additional formats may be added in the future by the website administrator.
Films should have a title, description, year they were released and a “star rating” out of ten stored against them.
Films are associated to none or more actor and actors can be associated to none or more films as some films may be documentaries (with no actors).
Films can be associated to one or more genre (such as action, adventure, Sci-Fi, etc).
The number of genres and actors may change so the website administrator needs to be able to add/edit as many genres and actors as they like over time.
Visitors of the website should be able to find films by browsing by actor or genre. When they do they should be able to see a list of all films that are associated to the actor/genre they have selected.
In order to buy from the website, visitors must register their details to become a user.
Users will have one or more addresses associated to their account. When they log in to the system in future all of their previously entered addresses should be available for them to select for their latest order. They should also be able to add a new address to their account at any time.
When ordering the user will select one or more items from the available films (in a particular format). They will need to select a billing and deliver address from those they have previously entered and pay for their order by credit card.
As the prices of the products can change over time the system should record what the price of each of the items in their order was at the time when they purchased as well as the total price of the entire order.
Tracking of stock levels is not required – all products can be assumed to be in stock all of the time.
If this is homework, or a class project, then you really need to start learning about normalisation. Take a look at the article on wikipedia or this introduction on the MySQL site
If this is a professional project, then you need professional help to design/develop your e-commerce site.
Here is something I could come up with, hopefully it should satisfy all the criteria mentioned in your requirements. I was designed in SQL Server as I do not have MySQL on this machine.
Steps to design the database (entity relationship modeling)
Identify the entities from the requirement. Entities are objects that hold information (usually denote real world entities like person, car, bank, employee, etc.). In your case, the entities identifiable are: Film, Actor, User, Order
Once you have identified the entities in your requirements, get down to the deciding the attributes (or properties) of the entities. The attributes are something that you associate the entity with. For example, one would identity a car by its manufacturer, model, color, engine capacity, etc. In your case, the attributes for the film entity would be Name, Genre, ActorInFilm(s), Format(s), Price
Identify the relationships between the entities. In your case, film has a relationship with actor. The relationship is: One film can have zero or more actors. And, one actor can act in one or more films. Thus film and actor are related.
Identify the cardinality of the relationships. Cardinality can be explained in simple terms as how many instance of the entity participate in the relationship.
For example, a employer can have 1 or more employees. And an employee can be employed by only one employer. In this case, there are 2 entities: Employer and Employee. They share the relationship employ. In your requirement, Film and Actor are the entities sharing the relationship Acts in (Actor(s) acts in Film). So the cardinality in this case will be one to many (Film to Actors)(one Actor can act in many Films) and zero to many (Actors to Films).
Once this part is done, you have your zero normal entity relationship diagram. Then comes the normalization. You can read about it on another post here.
After you have normalized the entity relationships (upto 3rd normal form is usually sufficient), you can implement the database design in the SQL design software (MySQL, etc.)
The best way to do the above steps is to take a sheet of paper and write the entities and attributes in a tabular format and then link them to other entities (to denote relationships).
You can refer any good book on database concepts (including normalization) or just search on google (keywords: database, normalization, database design, entity relationship modeling, etc.). What I have explained above is very brief, you will need to discover the rest of the database concepts yourself.
Entity relationship diagram is often abbreviated as ER diagram.