Relationship query: A company has many employees - entity-relationship

Lets say a relationship is described as:
A company has many employees
A company has many departments
A department has many employees
So, something like this;
Company -<< Departments >>- Employees
If department table has a basic structure of:
// Pseduocode
company_id // Foreign key
department_id // Primary key
[employees] // Array or collection of employees
If we go back to this phrase;
A Company has many employees
Does this mean that the employee table needs or requires a reference for the company_id too?
So, Employee would be:
employee_id
company_id // I'm not sure if this is requried or not
department_id
I'm intending to hopefully abstract this data into a contracts table in case of employees are freelancers/contracters, etc or have multiple employees.
But for now..
My question is:
Does my employee table require a reference to the company table, or is the company reference implied via the department table?
Many thanks

Question is: do you need a straight connection between Company and Employee? If you do, add it, if not then yes, the connection is implied through Department.
EDIT:
Technically, your Department table does not need a list of Employees. Each row of Employee table has a reference ID to Department, that's enough.
Check this out for more information.

The relationship is implied through the department, so you don't conceptually need it. Adding it, would be an example of denormalisation, and would allow inconsistencies to crop up. For example, you might have company_1 with department_1 and company_2. Now employee_1 might be linked to department_1 but company_2, because of some flaw/bug in the application code. There's no way to express this constraint as a SQL schema, so you'd have to go with more complicated stuff such as triggers, or application code checks etc.
However, sometimes you only need info about companies and employees, but not about departments. If it's really performance critical, doing the extra join with departments in order to find the company for an employee or the employees for a company might not cut it, so you'll just have to live with the denormalisation.

You probably do not need to link Company with Employee. The relation between Departement and Company already do the job. You may need it only if there are existing particular cases requiring this relationship.

Related

User and Customer in ER diagram

I'm having a scenario to create an ER diagram.
Scenario
There are Several Regions. One region can have several Business Chains. Each Business chain have one region to cover. One Business chain have several outlets. Customers can use this system to connect to any Business chain. Employees of a Business chain can be assigned to any outlet by the admin of the particular Business chain................
My Question is how am I suppose to handle user details and login details in the above ER diagram (or in the application)
Should I use two separate entities as "Customer" and "Employee"???
Should I use one entity as "User"? If so how to handle the above case of handling emplyees' roster
I suggest you combine customers, employees and users into persons, and use subtyping for each of the roles in which a person may occur:
I left out any indication of overlapping/disjoint subsets, you can fill them in based on your requirements. Implementing disjoint subsets would require adding some additional type indicators and check constraints to the tables below.
Physically, the diagram above would translate into a set of tables like:
person (person_id PK, first_name, last_name, ...)
user (person_id PK/FK, username, password_hash, ...)
customer (person_id PK/FK, credit_limit, ...)
employee (person_id PK/FK, salary, ...)
This allows any person with a user record to log in, and you can easily find out whether they're customers, employees (or both) by joining with those tables. You can create customer or employee-specific relationships easily, e.g.
outlet_employees (outled_id PK/FK, employee_person_id PK/FK)
where employee_person_id has an FK constraint referencing person_id in the employee table. You can also make user-specific relationships, or general person relationships, as your requirements dictate

E-R diagram confusion

I am in the process of designing this E-R diagram for a shop of which I have shown part of below (the rest is not relevant). See the link please:
E-R diagram
The issue that I have is that the shop only sells two items, Socks and Shoes.
Have I correctly detailed this in my diagram? I'm not sure if my cardinalities and/or my design is correct. A customer has to buy at least one of these items for the order to exist (but has the liberty to buy any number).
The Shoe and Sock entities would have their respective ID attribute, and I am planning to translate to a relational schema like this:
(I forgot to add to my diagram the ORDER_CONTAINS relationship to have an attribute called "Quantity". )
Table: Order_Contains
ORDER_ID | SHOEID | SOCKID | QTY
primary key | FK, could be null |FK, could be null | INT
This clearly won't work since the Qty would be meaningless. Is there a way I can reduce the products to just two products and make all this work?
Having two one-to-many relationships combined into one with nullable fields is a poor design. How would you record an order containing both shoes and socks - a row per shoe with SOCKID set to NULL and vice-versa for socks, or would you combine rows? In the former case the meaning of QTY is clear though it depends on the contents of SHOEID/SOCKID fields, but what would the QTY mean in the latter case? How would you deal with rows where both SHOEID and SOCKID are NULL and the QTY is positive? Keep in mind Murphy's law of databases - if it can be recorded it will be. Worse, your primary key (ORDER_ID) will prevent you from recording more than one row, so a customer couldn't buy more than one (pair of) socks or shoes.
A better design would be to have two separate relations:
Order_Socks (ORDER_ID PK/FK, SOCKID PK/FK, QTY)
Order_Shoes (ORDER_ID PK/FK, SHOEID PK/FK, QTY)
With this, there's only one way to record the contents of an order and it's unambiguous.
You have not explained very well the context here. I'll try to explain from what I understand, and give you some hints.
Do your shop only and always (forever) sell 2 products? Do the details of these products (color, model, weight, width, etc...) need to be persisted in the database? If yes, then we have two entities in the model, SOCKS and SHOES. Each entity has its own properties. A purchase or a order is usually seen as an event on the ERD. If your customers always buys (or order) socks with shoes, then there will always be a link between three entities:
CLIENTS --- SHOES --- SOCKS
This connection / association / relationship is an event, and this would be the purchase (or order).
If a customer can buy separate shoes and socks, then socks and shoes are subtypes of a super entity, called PRODUCTS, and a purchase is an event between CUSTOMERS and PRODUCTS. Here in this case we have a partitioning relationship.
If however, your customers buy separate products, and your store will not sell forever only 2 products, and details of the products are not always the same and will not be saved as columns in a table, then the case is another.
Shoes and socks are considered products, as well as other items that can be considered in future. Thus, we have records/rows in a PRODUCTS table.
When a customer places an order (or a purchase), he (she) is acquiring products. There is a strong link between customers and products here, again usually an event, which would be the purchase (or a order).
I do not know if you do it, but before thinking of start a diagram, type the problem context in a paper or a document. Show all details present in the situation.
The entities are seen when they have properties. If you need to save the name of a customer, the customer's eye color, the customer's e-mail, and so on, then you will have certainly a CUSTOMER entity.
If you see entities relate in some way, then you have a relationship, and you should ask yourself what kind of relationship these entities form. In your case of products and customers, we have a purchasing relationship there between. The established relationship is a purchase (or an order, you call it). One customer can buy various products, and one product (not on the same shelf, is the type, model) can be purchased for several customers, thus, we have a Many-To-Many relationship.
The relationship created changes according to the context. Whatever, we'll invent something crazy here as examples. Say we have customers and products. Say you want to persist a situation where customers lick Products (something really crazy, just for you to see how the context says the relationship).
There would be an intimate connection between customers and products entities (really close... I think...). In this case, the relationship represents a history of customers licking products. This would generate an EVENT. In this event you could put properties such as the date, the amount of times a customer licked a proper product, the weather, the time, the traffic light color on the street, etc., only what you need to persist according to your context, your needs.
Remember that for N-N relationships created, we need to see if new entities (out of relationship) will emerge. This usually happens when you are decomposing the conceptual model to the logical model. Probably, product orders will generate not one but two entities: The ORDER and the products of orders. It is within the products of orders that you place the list of products ordered from each customer, and the quantity.
I would like to present various materials to study ERD, but unfortunately they are all in Portuguese. I hope I have helped you in some way. If you want to be more specific about your problem, I think I can really help you best. Anything, please ask.

What is a many to many relationship?

I'm a bit confused on what a many to many relationship is. I'm wondering if the following is a many to many relationship:
A student at a school has many clubs. A club at a school has many students. Let's say that the student has many attributes: firstname, lastname, phone, age, email, etc. A club only has one attribute: a name.
When I make a new club, I want to be able to give the club a name and one or more students. Upon making the club, I want that club to be associated with those students and those students to be associated with that club.
When I make a new student, I want to be able to give the student a firstname, last name, etc, and one or more clubs. Upon making the student, I want that student to be associated with those clubs and those clubs to be associated with that student.
I also want to display a club's students and a student's clubs on their show pages.
I've read that a many to many relationship is when you have a join table that lets you access common attributes of the resulting students and clubs, but there are no common attributes in my case.
Do I have a many to many relationship here? If so, do I use a HABTM or has_many, through relationship?
Actually yes you DO have common attributes.
You stated yourself that a Student has many Clubs
And a Club has many Students.
What is in common? Students and Clubs.
What now follows is to define what a Student and a Club actually are, which you already did.
A Student is a combination of firstname, last name, etc... What you have not specified is what makes a Student UNIQUE. A club also must be defined as to what will make it UNIQUE. While for academic purposes, you could say the name is what makes it unique, in real live, that would probably not be the best solution.
Usually for performance purposes, each student is given a unique Autoincrement ID (which is a number).
Same thing can be done with the Club.
You create a 3rd table which is what creates the Many to Many relation.
In that 3rd table, you have 2 columns. One with the Unique Index for the Student, and the other column with the Unique Index for the Club. You simply add an entry on that table in which you wish to relate a student to a club.
Since you can have many students assigned to the same club, and you can have many clubs assigned to the same student, you have a many to many relation.
Edit: As mentioned in another answer, your 3rd table should also declare the combined indexes as unique, so that you don't add the same entry multiple times.
You have a many to many
Create an id for each table that is unique for that table typically an auto incrementing int.
Then a third table that is a junction/intersect table call it X.
Put a row in X with the student id and club id if the student has the club and vice versa. It would have a unique composite key in table X across both id's in it.
The composite would guarantee no duplicate rows in X
Yes indeed there is a many-to-many relationship here, use HABTM. Also, why do you say that there are no attributes in common? Club names and student names are definitely common attributes in this case.

Modelling Company and Person Customers in Rails

My Rails application uses STI where I have different types of companies and persons. For example I have suppliers, manufacturers and customers as types of Company. I have also employees, contacts and customers as types of People.
Now I want to refer to a Customer which can either be a Company Customer or a Person Customer. Which method can I use/should I use to combine these two different entities into one? So I can refer to a Customer, from an Order?
You could either use:
Order
belongs_to :company
belongs_to :person
end
And have two foreign keys - and then add some validations to make sure one of them is filled in, and then maybe add a 'customer' method which returns either the related company or person, depending which is used.
OR, create a separate Customer model (and table), which has those two same two foreign keys, and then Order can simply belong_to :customer. This second method may be preferably if you want to store additional data at the customer level (such as credit limit, or billing details), and may be cleaner long-term.
Alternative, you could reconsider your business logic, and insist that all orders belongs to a Person, even if that person is an employee of a Company and is purchasing on behalf of the company.
F

How to layout tables and relationships for MVC project

So I am working on an MVC project to put to work the studying I have been doing. I am wrestling with the concept of Database Table relationships and foreign keys. I am working on a simple ecommerce site (displays products, shopping cart, user accounts..etc).
I have the following tables to start out with:
1) Products
2) Categories
I setup the Products and Categories tables to have a ProductId and CategoryId respectively. In my MySQL db, I created a FK on the Products Table to relate to the CategoryId field on the Categories table (I am not sure this was correct to begin).
My expectations for the way the database would handle the table relationship: I didn't want the DB to do anything with the products table if I deleted a category out of the Categories table, or vise versa. The only thing would be that the category field in a Product would be blank (or default) if their category was removed.
Finally, do I have to do anything in my entity classes such as in the Products class, add the ProductId to the Category.ProductId?
Eventually, when I Orders and Users to the project, I can see a relationship where each user -> many orders -> each order has many products -> and each product is in one category.
But I am having a hard time understanding how or if I should be setting up a Foreign key relationship in the two current tables of Products and Categories and if so how to setup my entity class in relation to that FK.
Any advice.
It has been my experience (with L2S) that you don't want to specify any relationships between tables. I have simply done the PK, FK logic myself. This keeps the L2S generated objects simple and is most likely the way you worked with them before in SQL. That, at least, is the case for me.

Resources