Laravel's pivot table + Pivot table in general - php

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

Related

Laravel Eloquent belongsToMany

I have three db tables:
attributes
---------------------------------
| id | name | showed_name | class
attributes_profiles
----------------------------------------------
| id | attribute_name | profile_id | content |
profiles
------------
| id | ... |
When a User go on the profile site, I want to load ALL Attributes from the table, but I also want the content from the intermediate table (pivot) for this user (id).
public function Attribute(){
return $this->belongstoMany('App\Attribute', 'attributes_profiles', 'profile_id', 'attribute_name','id','name')->withPivot('content');
}
With this class in the profiles model, I wouldn't be able to get all attributes.
When I use a Profiles() Class in the Attributes Model, I get every Attribute but not the content for the user... but for every user.
When you use a Many-to-many relationship, you can access the intermediate table with the pivot attribute. I see you already have the withPivot directive in the relationship, so you are ready to go.
foreach($profile->attribute as $attribute) {
$attribute->pivot->content; // The content in the intermediate table
}

Joining more than two tables laravel 5.3 using eloquent orm

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');

How to remove a many-to-many relationship based on the Pivot Table information

I am in need to detach records from my pivot table, based on info stored in it.
So I have three tables, 1) Activity 2) activity_submissions 3) Submissions
One activity can have many submissions and one submission can have many activities, they share a many to many relationship. Now there is a catch: the activity_submissions table has a description column in it too.
This is the activity_submissions table:
id | activity_id | submission_id | desription
So I have three records as below:
1 | 20 | 1 | "First"
2 | 20 | 1 | "Second"
3 | 20 | 1 | "Third"
I only want to reove the one with description "Third".
I tried using detach, but that removes all of them:
$activity=\App\Activity::find(20);
$submissions=$activity->submissions()->where('submission_id','=','1')->get();
for($i=0; $i<$submissions->count(); $i++){
if ($submissions[$i]->pivot->description == "Third"){
$submissions[$i]->activities()->detach();
}
}
But this code detaches all my records, how would I go about doing this? I am using Laravel 5.0.
You can use ->wherePivot() function to filter out pivot table.
$submissions[$i]->activities()->wherePivot('description', '=', $yourVal)->detach();
In your case $yourVal = "Third";

How to return multiple relationships with Laravel Eloquent?

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.

Laravel eloquent many to many to many model

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).

Categories