Connect pivot table with multiple tables in Eloquent - php

I have this model:
User:
id (int)
name (varchar)
Role:
id int
name (varchar)
User_Role
id (int)
id_role (int)
id_user (int)
id_company (int)
What I need using Eloquent (Laravel 7), is to query user_role with the id_company:
This is my relationship into User model
public function rol() {
return $this->belongsToMany('\App\Models\Role','user_role','id_user','id_role');
}
This is my relationship into Role model:
function user() {
return $this->belongsToMany('\App\Models\User','user_role','id_role','id_user');
}
Is it possible to query the pivot table like this:
$user->rol->where(["id_company" => $params["id_company"]])->toArray();

You need to first include the pivot table columns in the relationship:
public function roles() {
return $this->belongsToMany('\App\Models\Role','user_role','id_user','id_role')
->withPivot('id_company');
}
Then you can query on the pivot table column:
$user->roles()->wherePivot('id_company', $params["id_company"])
->get()
->toArray();

Related

relationships with multiple pivot table Eloquent/Laravel

I have 4 table
users
id
name
school
id
name
user_school
id
user_id
school_id
user_role
id
user_role
role_id
We need to find school users list whose have role id is 2
we use belongsToMany but not success
public function totalAdmin(){
return $this->belongsToMany('App\Models\User','user_school', 'school_id','user_id')->where('user_school.status',1)->where('user_school.deleted',0);
}
Assuming you have relationships:
User-Role named roles (with pivot user_role)
School-User named users (with pivot user_school)
You can do:
School::users()->whereHas('roles', function ($q) {
$q->where('id', 2);
});
You can probably transfer it in the relationship as well:
public function totalAdmin(){
return $this->belongsToMany('App\Models\User','user_school','school_id','user_id')
->whereHas('roles', function($q) { $q->where('id', 2); });
}

Laravel: How can I get my friend relationship in a Pivot belongsToMany relation

I want to create a friendship relationship with another user in Laravel and when fetching the relationship, I want to get the user that isnt myself. (either user_id or friend_id)
This is the relationship I have:
return $this->belongsToMany(User::class, 'friend_user', 'user_id', 'friend_id')
->where('user_id', $this->id)
->orWhere('friend_id', $this->id);
When I am the user_id, I get the friend related
foreach($user->friends as $friend) {
echo $friend->first_name;
}
But when I am the friend, I get my own name. How can I solve this?
Thanks
You need two relations like below.
public function friends()
{
return $this->belongsToMany(User::class, 'friend_user', 'user_id', 'friend_id');
}
public function isFriendsWith()
{
return $this->belongsToMany(User::class, 'friend_user', 'friend_id', 'user_id');
}
Say a user with id 1 has two entries in the friend_user table like
id
user_id
friend_id
1
1
5
2
1
2
Then you can query relations like
$user1 = User::findOrFail(1);
$user1->friends; //Will get two users with an id of 2 and 5
$user2 = User::findOrFail(2);
$user2->isFriendsWith; //Will get one user with an id of 1
$user2->friends; //Will return empty collection
$user5 = User::findOrFail(5);
$user5->isFriendsWith; //Will get one user with an id of 1
$user5->friends; //Will return empty collection

Query table from model or controller in Laravel

I have table role_user which has two columns user_id and role_id. user_id is the user id from users table and role_id is the id from roles table.
I want to query role_user and show the role name next to each user. Example
table users
user_id username ...
1 Test user
table roles
role_id role_name
1 Admin
table role_user
user_id role_id
1 1
I want to show on page
Test user - Admin
I have added this in my Users model
public function role()
{
return $this->hasOne('App\Role', 'user_id', 'role_id');
}
and this in the controller
public function users()
{
$userRole = User::find(1)->role;
return View::make('users', [
'userRole' => $userRole
]);
}
Currently I've got this which is obvious why:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.user_id' in 'where clause' (SQL: select * from roles where roles.user_id is null and roles.user_id is not null limit 1)
The question is how to query role_user table from controller or from model and while displaying the users to display role name too.
You have defined your table so one user can have many roles (using a pivot which is your role_user table.
If a user can only have one role you can remove the role_user table and add a column role_id to your users table.
Using your current implementation change role relationship in user model to following.
public function roles()
{
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
}
In your controller
public function users()
{
$users= User::with('roles')->get();
return View::make('users', [
'users' => $users
]);
}
To simply show the names of roles use implode method of returned collection
#foreach ($users as $user)
{{ $user->roles->implode('name', ',') }}
#endforeach
You are using a pivot table to maintain the relationship so you need to
belongsToManyrelation and defining a custom accessor for it, like so:
//User model file
public function roles()
{
return $this->belongsToMany(App\Role::class);
}
public function getRoleAttribute()
{
return $this->roles()->first();
}

Laravel Eloquent Relationship custom query

I have 2 tables: USERS and SUBJECTS
The relationship between USER and SUBJECT is many to many.
In the User.php and Subject.php models, I defined:
User.php
function subjects() { return $this->belongsToMany('App\User'); }
Subject.php
function users() { return $this->belongsToMany('App\Subject'); }
The pivot table is subject_user and it has 3 columns:
subject_id, user_id, finished
The finished value can only be between 0 and 1.
Now I know that when I want to select all the subjects that an user studied, I have to write $user->subjects.
But what if I want to select all the subjects that an user studied and the finished value in the pivot table is equal to 1?
You need to add "withPivot()" to your relationship definitions, like this:
function subjects() { return $this->belongsToMany('App\User')->withPivot('finished'); }
function users() { return $this->belongsToMany('App\Subject')->withPivot('finished'); }
Then you can do:
$user->subjects()->where('finished', 1)->get();
You will need to eager load that relationship and use the wherePivot method.
$user = User::with(['subjects' => function($q) {
$q->wherePivot('finished', 1);
}])->fine($user_id);

Relationship between a hasMany and belongsToMany in Laravel

I have two Models - InternalNotesThread and InternalNotes
class InternalNotesThread extends Model {
public function notes(){
return $this->hasMany('App\InternalNotes', 'thread_id', 'id');
}
}
class InternalNotes extends Model {
public function thread() {
return $this->belongsTo('App\InternalNotesThread');
}
public function users()
{
return $this->belongsToMany('App\User', 'user_notes_tagged', 'internal_notes_id', 'user_id');
}
}
Also, InternalNotes is mapped to User with a relation of belongsToMany.
DB Structure:
internal_notes_thread:
id - int
ticket_id (FK) - int
name - string
internal_notes:
id - int
thread_id (FK) - int
notes - string
user_notes_tagged: (Many to many with internal_notes and User)
internal_notes_id (FK) - int
user_id (FK) - int
For every note, there might be some user tagged in it.
How can I directly relate this relationship with the internal_notes_thread???
I get the data with this:
$data = InternalNotesThread::with('notes')->where('ticket_id', '=', $id)->get()->toArray();
But, in the notes array, I am not able to get the users tagged in that note
How can I get all the data in one go???
You're not eager loading the users, so they don't show up in your ->toArray() array.
Try this:
$data = InternalNotesThread::with('notes.users')
->where('ticket_id', '=', $id)
->get()
->toArray();

Categories