belongsToMany -> belongsToMany Laravel - php

Edit*
Im pretty happy with my DB setup. I want to know the 'Laravel way' to query this data and update it.
Just after a bit of advice on the best way to structure this and update the data! Im working on a platform for nurseries. Children can be assigned to a room each day of the week; either morning, afternoon or full day. I currently have the following (forget the room_child pivot for now)
child Model
id
name
daysOfWeek Model
id
day
child_days pivot table
child_id
day_id
dayType Model
id
type
1
full
2
morn
days_type pivot
day_id
type_id
So - Want to be able to book each child in for each day of the week, possibly two different types per day. Morning and evening.
EG
child 1 -
Monday
Morning
Tuesday
Full Day
Wednesday
Afternoon
Any advice on best way to do this and how to manage it? As in, can I eager load the results or something?

This is more of an opinion than an answer so take it with a grain of salt.
I wouldn't use a daysOfWeek model/table at all.
Why bother? You will end up with a database table that will only contain 7 rows and will never need to grow or shrink. DayType can stay. Maybe in the future you'll have more types. At least, that's more likely than the definition of a week being changed.
This removes the need for the child_days and days_type pivot tables.
In the end you're left with just 3 models.
Child
DayType
Booking (or however you want to call it. )
The relationships will be as simple as
Booking belongsTo Child
Booking belongsTo DayType
Child hasMany Booking
DayType hasMany Booking
The bookings table I'm imagining has the following columns.
id (pk)
child_id (fk)
day_type_id (fk)
day (could be varchar(9) or enum('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'))
Enum makes a bit more sense. If you use them you might be interested in Enum Casting

Related

Laravel sync a Pivot table with 3 models relationships Many to Many and One to Many

Information:
A sound company has many employees.
The employee has many positions in the company.
The company has many events. And for every event, they need a crew.
A crew is composed of many employees holding certain positions. An employee can hold multiple positions in a crew.
For example:
The list of employees is:
Employee 1 is a Driver, Sound Engineer and Stage Hand
Employee 2 is a Driver, Sound Engineer
Employee 3 is a Sound Engineer and Stage Hand
Employee 4 is a Stage Hand
Employee 5 is a Stage Hand
The event is called: Event 1
The crew is:
For the position of Sound engineer:
Employee 1
Employee 2
For the position of Stage Hand:
Employee 3
Employee 4
Employee 5
For the position of Driver:
Employee 2
Employee 1
Problem:
I believe this is done by using a pivot table that holds the event_id, employee_id and position_id
But when I follow this approach, I get stuck on feeding the data and the methods to use to create new data.
Is there a different approach?
you need two pivot tables. One for employee and position which hold employee id and position id. Another one between employee and event which holds event id and employee id. I think this is a better way to handle this. You can use the attach and detach method handling pivot table in laravel.

Four-(or five-)way Table Relationship in Laravel

I have tried reading Laravel documentation and other, similar posts about Laravel database relationships, but I cannot seem to wrap my head around it and how it applies to my use case.
I run a web site for high school athletics. I have 5 tables:
schools - Standalone list of all schools in the state.
sports - Standalone list of all sports sanctioned by the state.
seasons - Standalone list of seasons (one season per school year).
leagues - Standalone list of leagues/conferences.
league_divisions - List of divisions for leagues that have multiple divisions (think "Big Ten East" and "Big Ten West") where leagues = parent and league_divisions = child. Note: A league would only have child records in this table if it had divisions; Most high school athletic conferences/leagues do not have divisions, and therefore would not have a corresponding record in this table.
Every so often, schools change leagues, or may change which division of a league they are a part of. (think "school_leagues")
Similarly, a school may begin to field a new sport (School A never had girls soccer in the past, but now they have a team) or discontinue an old one (School B no longer has a football team). (think "school_sports")
Also, while the state may sanction 25 sports, a league itself may only sanction 10. My web site is for the League itself, so I would also need a way to list which sports a league sanctions. (think "league_sports")
In my old (pre-Laravel) data model, I just had a "school_leagues" table that stored what league (and division, if applicable) a school belonged to for a particular range of seasons (via start_season_id, end_season_id). Additionally, in the HTML, I simply hard-coded a static list of which sports a league sanctioned and which teams should appear in that sport's standings.
However, as I rebuild my data model, I'm thinking I may need a more complicated relationship table(s) that joins Schools, Sports, Seasons, Leagues, and (optional) League Divisions.
Additionally, instead of using start_season_id and end_season_id (where end_season_id IS NULL if the relationship is still valid), will Laravel conventions force me to have 1 record per school per sport per season per league/division? (This would directly join to season_id as opposed to having start/end_season_id columns)
Any help is appreciated!
I could simply go with 3 relationship tables: school_leagues, school_sports, and league_sports, and all would join to season by either season_id (1 record per year) or start/end_season_id.
OR I would have 1 master table that joins school_id, sport_id, season_id, league_id, and (optional) league_division_id. It would have 1 record per instance, so each year I'd generate a new group of records.
Laravel / Eloquent has a serviceable scheme for many-to-many relationships. https://laravel.com/docs/5.8/eloquent-relationships#many-to-many In your app you have several many-to-many relationships, for example schools >----< sports . Eloquent uses a join table (called something like schools_sports to represent this in the DBMS.
To handle the complexity here, you probably need a new entity in your database design. Let's call it teamseason. There's one of these for each school, sport, season, and league. It relates to one each of those entities, and it might have attributes like won, lost, captain, and other data points relating to the team and season.
For example,
Stuyvesant High School (school) had a
Precision Air Rifle (sport) team
In Spring 2018 (season) playing in the
New York City Geeksports League (league)
They won 10 and lost 3 matches, and the captain was Deadeye Robinson (attributes)
You'll need another of these entities for the Spring 2019 team.
A table for it might look like this:
teamseason_id PK
school_id FK to school.school_id
sport_id FK to sport.sport_id
season_id FK to season.season_id
league_id FK to league.league_id
won int
lost int
captain varchar(128)
I'd throw in division, but I don't understand the structure.
This looks like it might be some kind of four-way join table, but it's more than that. I added the won/lost/captain attributes to emphasize that it's its own entity.
The trick is to identify an entity for each real thing in the world of your app, then identify the relationships between entities. (It takes practice to do this well.)

How to normalize my MySQL Database

I have PHP/MYSQL car rental site. In the MYSQL table i store
car license plates
car specs (like AC, brand and such)
price per day (30 colums), since price for 1 day is X euro per day, and for 30 days let's say is Y euro per day
insurance per day (this is a per
car thing because it depends on the specific car history, year,
brand, model and such). So since there are 30 days in a month, we
have here another 30 columns, since insurance for 1 day <> insurance
for 28 days let's say
Now if i put all this stuff in I will have about 70 colums.
Any smarter way of doing it to avoid a performance blow?
I do not control the prices and there is not a daily price or daily insurance formula.
One ideea would be to use the car plates as an index and blow it in 2 tables, one with prices (35 rows), one with insurance (35 rows). Any other?
The DB has 1000 cars or so. I get about 10.000 queries a day in the DB
Kind thanks.
A quick an dirty attempt below. I'd move prices and insurence costs in dedicated tables, each having a car_id and days field.
Select brand,type,ac,seats FROM cars
LEFT JOIN prices ON cars.id = prices.car_id
LEFT JOIN insurence_costs ON cars.id = insurence_costs.car_id
WHERE
licensePlate = 'HH-OH-234'
AND prices.days = 28
AND insurence_costs.days = 28
Update: Added the license plates. I'd just put them in car specs. In general they are car related but may change sometime in future. If they change quite often I'd rather move them in a dedicated table too.
I would actually save the price per renting day depending on the overall renting span to the db. That way, you could do something like
SELECT price FROM prices
WHERE car_id = 123 AND days = MAX(days);
That way you could multiply the "last" price with the actual amount of renting days for any rents above 30 days. But thats up to pricing definitions.
To normalize a database (or more general to design a database) you have to, clearly, determine the entities that you have.
From your description, you have four entities as follows:
Car
Specification
Price
Insurance
Every entity of the above should has a table to handle its properties (columns).
After, defining the entities, the real normalization is to define the relations between the entities, either through, keys properties (columns) or through new entity (table), for example, in Many to Many relations. Lets discus the relations:
Car: one car should has one specification, price and insurance. i.e the relation is one to one. So, cars table should has specification_id, price_id and insurance_id columns that relate it with the other three tables.
On the other hand the other three tables (entities: specifications, price and insurance) may have many cars so its relation to car is one to many and it is covered by defining the foreign keys in the cars table (specification_id, price_id and insurance_id)
How could it work?
Before inserting new car, you have to complete the other entities. In other words, a list of all available, specifications, prices, insurances should be found in there respectable tables (entities) and if you have got a new car that has no any defined one of them, then you have to create new entity that covers its need before inserting or creating it. i.e inserting new specification and/or new price and/or new insurance that car should belong to.
Notice: this is not a law, you or other one may able to invent another entities relations. However, what I have regarded here is a
general hint based on relational database design methodology

How to fetch data of one table column into another table row

I have 7 tables one is faculty_subjects rest are Monday,Tuesday,Wednesday,Thursday,Friday and Saturday my tables structure is like this
i have attached image url
http://s27.postimg.org/434y3255f/School_Management_System.jpg
i tried to make whole design here but everything mashedup
live static page http://www.school.eptins.com/
when someone select class and section relevent to that subjects and faculty display in fields.
I think time-table for one class is a table in itself. Instead of scattering time-table information of a classroom over 6 different tables, you could keep a table name timetable_IA and that table could have first column for periods (Period I, Period II, Period II, ...) and second column for subjects on Monday, third column for subjects on Tuesday, etc.
That way, when a person chooses class IA, you have to just gather information from one table only.
For the second table (Subject Faculty), you could make an array of subjects appearing in time-table by reading time-table of IA, and then call in names of faculty teaching those subjects and construct the table.

Schema advice for minibus booking system

I'm developing with CakePHP 2.0 and MySQL.
I'm trying to create a minibus booking solution but I'm unsure if I'm following the right approach.
We have one minibus which we can book out. I'm not bothered about booking times overlapping at this stage. I've made a table for the minibus properties but I need to define the relationship between the minibus and the passengers.
Each minibus can have many (16) passengers.
A passenger can travel on more than one minibus (one today, one tomorrow etc).
Also I need to be able to set the type of passenger to either passenger or driver.
Will this need three tables? I was thinking:
Buses table (id, description)
Users table (id, firstName)
Passengers table (buses.id, users.id, passenger_type)
Any advice would be appreciated.
I think I would introduce a Trip table and assign the bus to an instance of a Trip. Then introduce a junction table to resolve the many-to-many relationship between Trips and Passengers.
Given that one minibus can service many passengers, and one passenger can ride on many minibus routes, then what you have is a many-to-many (m-to-n) relationship.
Therefore, you'll need three tables: one for Passenger, one for Minibus, and one that relates the first two via key associations:
Passenger_Minibus
------------------
PassengerID INT NOT NULL
MinibusID INT NOT NULL
It will look something like this:
One table to store capacity of the minibus. (CapacityId)
One table to store passenger information. (PassengerId, Name, address etc)
One table to store Minibus information. (MiniBusId, CapacityId, Make, Model, Year, color etc..)
One table for BookingInformation(BookingId, date, time, FromDestination, ToDestination etc)
One table for TripSchedule(TripId, BookingId, MinibusId)(Only if you have multiple buses per booking else you can add MiniBusId to BookingInformation table and get rid of this table)
One Link table to store TripId and PassengerId. (If you have only one minibus per booking, add BookingId instead of TripId)

Categories