I'm doing a project in laravel 4, and I have come to a stop.
tasks table:
task_id (PK)
task_title
measurements table:
measure_id (PK)
measure_title
routines table:
routine_id (PK)
date
time
value
emp_id (FK)
emps table:
emp_id (PK)
first_name
last_name
user_name
email
user_type
Now what I am confused about is how I would model these relationships in eloquent, because I can't seem to figure it out. In the phpmyadmin DB, I currently have two tables connecting the tasks and measurements to routines which have task_routine : task_id (PK), routine_id (PK) and measure_routine : measure_id (PK), routine_id(PK).
Hope that was as clear as it sounded in my head when I wrote it, and thanks for your help!
At first in your all tables change the PK field from *_id to just id. If you want to make a relation for a table with another table then the convention is that, you should keep a foreign key in the child table using the parent table's name_id (name should be in singular form), for example, to build a relation between emps and routines table you should use emp_id foreign key in the routines table and your emps table should contain id PK. So, your emps table is parent table and the routines is the child of emps and in both tables records should be like this (custom convention could be used):
Table emps (parent):
id (pk) | first_name | more fields ...
1 | Mr | ...
2 | Miss | ...
3 | Mrs | ...
Table routines (child):
id (pk) | emp_id (FK) | more fields ...
1 | 1 | ... - Child of emps table's first record
2 | 3 | ... - Child of emps table's third record
3 | 3 | ... - Child of emps table's third record
Here, each id of emps table used as foreign key in the routines table in emp_id field. So, emps table has three related records in routines table and the first record in emps table relates to first record in the routines table and the third record in the emps table (with id 3) has two related records in routines table (second and third) because both records contains id 3 of emps table's third record in emp_id field.
Now building relation using Laravel:
If your parent table has only one related table in child table then use one-to-one, for example, if the record with id 1 (first record) in emps table has only one related record in routines table using emp_id field with value of 1 and if it can't be in more than one record in the routines table then it's one-to-one relation and in the example records given above is not one-to-one relationship because in the routines table there are two records with same id/pk of emps table available so it goes to one-to-many relationship, so it could be read as emps on record has many routines. To build the one-to-many relation we may use:
class Emp extends Eloquent {
public function routines()
{
return $this->hasMany('Routine');
}
}
The Routine model:
class Routine extends Eloquent {
public function emp()
{
return $this->belongsTo('Emp');
}
}
In one-to-many relationship a parent table may contain multiple child records with same id but if a record in child table has many parents as well then it should be a many-to-many relationship. For example, if we want to build a relation in routines table something like this (Not possible to use same primary key twice):
id (pk) | emp_id (FK) | more fields ...
1 | 1 | ...
2 | 2 | ... - Record 2(id) has parent 2(emp_id)
2 | 3 | ... - Record 2(id) has also parent 3(emp_id)
In this case this is a many-to-many relationship and it's not possible to use same id/PK twice in one table so we need to build the many-to-many relationship between emps table and routines table using a third table (known as pivot table) to maintain the many-to-many relationship. So, it'll look something like following table:
Table Name should be emp_routine but there is other way to use a
different name but follow this convention.
emp_routine Pivot Table:
id (pk) | emp_id (id/PK of emps) | routine_id (id/PK of routines) | more fields ...
1 | 1 | 1 | ...
2 | 2 | 1 | ...
3 | 1 | 2 | ...
Here, both parent and child has more than one related records in both tables and this pivot table maintains the relationship.
To build the relationship using Laravel we may use:
class Emp extends Eloquent {
public function routines()
{
return $this->belongsToMany('Routine');
}
}
The Routine model:
class Routine extends Eloquent {
public function emp()
{
return $this->belongsToMany('Emp');
}
}
In this case, we don't need a foreign key field (emp_id) in the routines table because we are using a pivot table to maintain the relationship but if it's there, it won't be problem.
It should be notice that whenever you insert/update any record in the parent table you also have to insert/update relational data in the pivot table as well and Laravel provides helpful methods for these, so check the manual (relationship).
Related
Request table:
ID | Acrid | Type-id
User table:
ID | Acrid | Dptid
Department table:
ID | Code
Type table:
ID | Name
'Request' table has one to one mapping with 'User' & 'Type'
This we can get using Request::with(['user','type']);
The user table has one to one mapping with the department table.
My question here is how to get the department details which is not related to the request table but related to the user table?
You can write for multiple eager loading relation:
Request::with('user.type');
What are laravel pivot tables and pivot tables in general? What is this all about?
Recently I made research about Pivot table. I thought I know them and What they are but then I probably was wrong about that.
I have always thought that a pivot table is just a table that is between two tables (Relation many to many)
But then I started this research and It happened to be not that, but something like different architecture of normal table, where rows are columns. It's changed.
But then Laravel's got pivot tables too. Started reading the documentation and doing research.Maybe I read wrong, but it looks like just pivot table in laravel - table in between two tables, many-to-many.
Searching elsewhere but can't find proper information about it.
Okay, so be it. Laravel's pivot just many to many!
Then I started project and Today I went to the point that making this in-between table as pivot drived me to an Issue, I had a problem with that... minutes and hours... couldn't fix that.
Model was class Room_Student extends Pivot
And what was the fix? Just changing it to class Room_Student extends Model.
I don't think I understand pivot tables anymore and are they different types of pivots? Laravel's pivots are different?
So my question is, what pivot tables really are? + Laravel's pivot tables. Are they different? What is this about?
Please help me understand this.
When learning, focus only the pivot tables concept in Laravel (or eloquent). When I was learning I did not care about the general meaning of pivot table. I focused only on facts in the documentation (https://laravel.com/docs/5.5/eloquent-relationships#many-to-many)
many-to-many relationships require an additional table.And we can insert other useful data to this table as well. And can be used as a model in the system.
Example :
User and Roles many-to-many relationship = User_roles
Because of Pivot tables, you can retrieve intermediate table data as a model (like other models in the system).
Example:
//get user by id
$user = App\User::find(1);
//get roles of this user
foreach ($user->roles as $role) {
//pivot attribute returns a model which represent user_role table
echo $role->pivot->created_at;
}
NOTE: you can create a class by extending pivot. But you have to implement the correct relationships to make it work. Your code should look somewhat similar to below code.
class Student extends Model
{
/**
* The users that belong to the role.
*/
public function Rooms()
{
return $this->belongsToMany('App\Room')->using('App\Room_Student');
}
}
class Room extends Model
{
/**
* The users that belong to the role.
*/
public function Students()
{
return $this->belongsToMany('App\Student')->using('App\Room_Student');
}
}
class Room_Student extends Pivot
{
//
}
I hope this helps.
Simply put is a pivot table a table that joins two tables together
say you have a table users
USERS:
user_id, user_name
say you have a table games
GAMES
game_id, game_name
a user can play many games. games have many users playing them.
To link them you make a third table
GAMES_TO_USERS
game_id, user_id
with this table you can request which games a user plays, and which users play which game.
this table GAMES_TO_USERS is in this case the pivot table.
If you know about many-to-many relationships this is common, to handle many-to-many relationships we use intermediate (pivot) table to store relationships of two tables.
Ex: consider about “education” and “person” tables which are listed below
table: person
|------|-------|-----|
| id | name | age |
|------|-------|-----|
| 1 | Bob | 30 |
| 2 | John | 34 |
| 3 | Marta | 28 |
|------|-------|-----|
table: education
|------|-------|
| id | level |
|------|-------|
| 1 | BSc |
| 2 | MSc |
| 3 | PhD |
|------|-------|
Think that Bob has BSc, MSc and John has BSc, MSc, PhD and Marta has BSc, now this is consider as many-to-many relationship and to sort this relationship you need to have intermediate table such as,
table: person_education
|------------|--------------|
| person_id | education_id |
|------------|--------------|
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 2 | 1 |
| 2 | 3 |
| 3 | 1 |
|------------|--------------|
This table mainly stores the primary keys (IDs) of each relationship. This is the basic idea behind the pivot table and when you use larval there are some best practises such as,
Name of the pivot table should consist of singular names of both
tables, separated by undescore symbole and these names should be
arranged in alphabetical order
Laravel Ex:
Class Person extends Model {
public function education ()
{
return $this->belongsToMany('App\Education', 'person_education');
}
}
Moreover, you can specify the actual field names of that pivot table, if they are different than default person_id and education _id. Then just add two more parameters – first, the current model field, and then the field of the model being joined
public function education() {
return $this->belongsToMany('App\Products', 'products_shops', 'shops_id', 'products_id');
}
Keep this in mind
Pivot table — is a table used for connecting relationships between two tables.
Laravel part — laravel provides many-to-many relationship where you can use pivot table, and it is very useful for many cases.
Example:
databases: users, post_user, posts
User.php (Model)
class User extends Model{
public function posts(){
return $this->belongsToMany('Post');
}
}
Now, to access all posts of authenticated user: (view)
#foreach(auth()->user()->posts as $post)
<li>{{ $post->name }}</li>
#endforeach
Relationship happened:
Remember we have post_user table which is the pivot table we used. If we have:
user_id of 1 and we expect that it is the logged in user and post_id of 1, 2, 3, 4, all this posts will be printed out like so:
|------------|--------------|
| post_id | user_id |
|------------|--------------|
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 1 |
|------------|--------------|
Output:
PostName1
PostName2
PostName3
PostName4
I have a table called users. Each of these users has different things:
country
device
computer
category
I have created a table for each of these above 'things'. Similar the following:
1 | United States
2 | United Kingdom
3 | Australia
4 | Canada
5 | Italy
etc...
I'm storing these values in the users table as follows:
ID | Country | Device | Computer | Category |
---|---------|--------|----------|----------|
1 | 3 | 2 | 6 | 2 |
2 | 4 | 3 | 9 | 1 |
etc...
Now each of the above numbers are associated with the corresponding table's ID.
What I want is do an Eloquent Query and search for all the users and 'replacing' their corresponding values from their helper table.
I was thinking about doing a hasOne() Eloquent relationship for each of those things in the users table, but then I'm not sure how to get/call them at once.
Anyone can help me tacke this issue?
$model = Model::with('relatedModel', 'relatedModelTwo')->get();
So in your case, it can be something like this. If you only want one relations returned with the user, remove the others.
$user = User::with('country', 'Device', 'Computer', 'Category')->get();
When you dd($user), you should see the related models in the relations array attribute.
To access the relations' properties from there, it is simply
$user->device->deviceAttribute
Edit For Comment:
Eloquent will assume the foreign key uses the Model name. So if your user table has the id column, it assumes there will be a column on device table called user_id. If you did this, then you are set and nothing should have to be done.
If you named your column to relate the models something else, you will need to pass that through as a second argument in the relation method.
public function device()
{
return $this->hasOne('App\Device', 'foreign_key_here',);
}
Inversely, if you wanted to get the user the device belongs to, Eloquent will attempt to match the user_id column on the device table to the id column on the user table. As before, if you used a different column to related them, declare the foreign key as the second argument.
public function user()
{
return $this->belongsTo('App\User', 'foreign_key_here',);
}
Laravel Doc One-To-One Relation
You're looking for this: $books = App\Book::with('author', 'publisher')->get();
Check out the documentation for eager loading multiple relationships.
I want to design an application, where we can add many category and each category can have a parameters. And I want to create a new product to the category and her parameters. Relations between
parameters and category is many-to-many (categories_table, parameters_table)
Category "Test" parameters:
id | key | type | def_value |
==============================
1 | color | text | red
==============================
2 | serial| text | 0
etc.
And now i want to create a new product with those parameters, so i have a question. Should i simply create many-to-many or maybe create new table with records like parameters ? Ex,
test1_table -> color, srial, etc.,
Or
products -> parameter_id,value
cause the relationship is many to many you have to create another table with the columns that are the foreign keys in the relation ---
tip: because you will have a table called category and each category can have parameters you should create another table with a foreign key that have the parameters
example
table_category - record 1 :color
table category_parameters - record
1 : color,azul -- record 2 : color,verde etc
and the foreign key is the primary key of category in this case ('COLOR')
I'm new to database design so please bear with me. I'm using PHP and MySQL.
I have a 'movies' table that contains some details about a movie. This includes genres, which have an (if I understand correctly) many to many relationship with movies, implying a single movie can belong to different genres and a single genre can belong to different movies.
From what I gather about database design, storing this kind of relationship in one table is not a good idea as it will either violate First Normal form or Second Normal form rules.
How would I design my tables to avoid this; would I have to create a table for each genre separately or... ?
This leads my to my next question: separate tables need to have foreign keys to identify which information belongs to what row. In theory, if I had a unique key identifying each movie which I would then like to use to identify a director in a separate table, how would I create this relationship in MySQL?
Thank you for your time - if I've made anything unclear please let me know and I will try my best to clarify.
This includes genres, which have an (if I understand correctly) many
to many relationship with movies, implying a single movie can belong
to different genres and a single genre can belong to different movies.
That's right.
From what I gather about database design, storing this kind of
relationship in one table is not a good idea
Right. You're looking for something loosely along these lines.
create table movies (
movie_id integer primary key
-- other columns
);
create table genres (
genre varchar(15) primary key
-- other columns?
);
create table movie_genres (
movie_id integer not null,
genre varchar(15) not null,
primary key (movie_id, genre),
foreign key (movie_id) references movies (movie_id),
foreign key (genre) references genres (genre)
);
For directors, assuming there is only one director per movie, you can use this instead of the movies table above
create table movies (
movie_id integer primary key,
director_id integer not null,
foreign key (director_id) references directors (director_id) -- not shown.
-- other columns
);
You need one table Movies, one table Genres and one table Movies_and_Genres. The first two contain unique primary keys which you can create using the mysql autoincrement field type. The third table contains pairs of those primary keys.
create table movies (id integer not null primary key auto_increment, title ... );
create table genres (id integer not null primary key auto_increment, genre ... );
create table movies_and_genres (id_movie integer not null, id_genre integer not null);
As for the directors, this is a question of data modeling. If a movie can have more than one director, then you need a directors and a movies_and_directors table. Otherwise you need only the directors table and a director column in the movies table.
you need/should use junction tables
table movie:
| id | title | rating |
-----------------------
| 1 | foo | 5 |
| 2 | bar | 4 |
table genre:
| id | name |
----------------
| 1 | comedy |
| 2 | romance |
table director:
| id | name |
----------------
| 1 | hello |
| 2 | world |
table movie_genre:
| id | movie_id | genre_id |
----------------------------
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 1 |
table movie_director:
| id | movie_id | director_id |
-------------------------------
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 2 | 2 |
You're quite right, what you need here is to have a table of movies (e.g. tbl_movies);
pk id
name
... etc
a table for genres (eg tbl_genres);
pk id
name
... etc
and a table linking the two (eg tbl_movie_genres);
fk id_movies
fk id_genres
You can either set the pk of the tbl_movie_geners to be the two foreign keys, or you can set a standalone pk (e.g id like in the tbl_movies and tbl_genres tables above).
this way you can list as many genres per movies and they're linked through the tbl_movie_genres table; eg:
tbl_movies:
id name
1 Movie 1
2 Movie 2
tbl_genres:
id name
1 Horror
2 Action
3 Rom Com
tbl_movie_genres
id_movies id_genres
1 3
2 1
2 2
Would show you that 'Movie 1' is a rom com and 'Movie 2' is an action horror.
To satisfy the many-many relationship use a join table that holds foreign keys to both the movie and genre tables:
MOVIE
-----
ID (PK)
GENRE
-----
ID (PK)
MOVIE_GENRE
-----------
MOVIE_ID (FK that references MOVIE(ID))
GENRE_ID (FK that references GENRE(ID))
Here the MOVIE table has a primary key of ID, the GENRE table has a primary key of ID, and the MOVIE_GENRE table has two foreign key references: one to MOVIE.ID and another to GENRE.ID. The primary key for MOVIE_GENRE could either be the composite key of (MOVIE_ID,GENRE_ID) as that will be unique but you could use a synthetic key as well.
For dealing with the director table and relationship, if it is a one-to-many relationship (one director for many movies), simply add a foreign key to the MOVIE table:
DIRECTOR
--------
ID (PK)
MOVIE
-----
ID (PK)
DIRECTOR_ID (FK TO DIRECTOR(ID))
If the off chance you need to support another many-to-many relationship (many directors for many movies), use the join table approach like above.