Laravel count roles of user based on another table - laravel

I have a table of Employee which has organisation column with different names, each organization has employee and employer role, i want to fetch organization name and count total number of employee and employer
like that with keys
['organisation' => 'UAE Hospital'
'Employee' => '10'
'Employer' => '5']
i have try this so far but it shows N+1 Query.
$data = Employee::where("organisation", 'UAE Hospital')
->select('organisation')
->whereHas("user.roles", function ($query) {
$query->where("id", '2');
})
->OrWhereHas("user.roles", function ($query) {
$query->where("id", '3');
})
->get()->toArray();
For roles i am using spatie package.

Related

How to query count on the pivot table in Laravel eloquent

I have two data tables in database. One is user table, other one is property table. User can save as many properties as they want. Also, one property can be save by multiple users. So there is a pivot table which has the property_id and user_id in it for a record. Now I want to query the popular properties. All properties that is saved by more than 100 users are popular properties. How would I do that? Something like I am doing
public function popularProperties(Request $request)
{
$id = $request->id;
return Property::where('saved'->count(),'>',100)->with([
'paymentPlan' => function ($query){
$query->select('property_id','all_in_one_go','down_payment','minimum_installment_per_month');
},
'city',
'propertyType' => function ($query){
$query->select('id','name');
},
'user' => function ($query){
$query->select('id','name','email');
},
'images' => function($query){
$query->select('imageable_id','url');
}
])->withCount('likes')->get();
}
The following code selects all property's with > 100 count. Inside the whereIn is a subquery that selects all property IDs that exist > 100 times. Note that you have to fill in the correct Table and column names
$propertys = Property::whereIn('id', function ($q){
$q->select('property_id')
->from('user_property')
->groupBy('property_id')
->havingRaw('COUNT(*) > 100');
})->get();

Laravel 5.2 Eloquent ORM to get data from 3 tables

I have the following tables. users, user_details and client_teams. Each user has one details and each user can have many teams. schema for users:
id, name, email,parent_user_id
user_details:
id, user_id, client_team_id
client_teams:
id, user_id, team_name,status
In user_model i have the following relations:
public function userDetails(){
return $this->belongsTo('App\Models\UserDetails','id','user_id');
}
public function clientTeamList(){
return $this->hasMany('App\Models\ClientTeams','user_id','id');
}
In user_details model i have the following relation:
public function clientMemberTeam(){
return $this->belongsTo('App\Models\ClientTeams','client_team_id');
}
I want to be show the list of users who have a specific team ID and created by a specific user. The query that i am using is this:
$userCollections=Users::where([
['users.status','!=','DELETE'],
['users.parent_user_id',$clientId],
['users.id','!=',$loginUser->id]
])
->with([
'userDetails'=>function($query) {
$query->where('client_team_id',1);
}
]);
This is giving me all records for this user, Whereas i want to match by client_team_id and user_id
You need to use whereHas and orWhereHas methods to put "where" conditions on your has queries.
Please look into https://laravel.com/docs/8.x/eloquent-relationships
$userCollections = Users::where([['users.status', '!=', 'DELETE'],
['users.parent_user_id', $clientId],['users.id', '!=', $loginUser->id]
])
->whereHas('userDetails' => function ($query) {
$query->where('client_team_id', 1);
})->get();

Access column of target table after calling relationship - Laravel

I have three tables as follows
Base Table
users
id - integer
name - string
Target Table
roles
id - integer
name - string
Pivot Table
role_user
user_id - integer
role_id - integer
Many to many relationship is exist between users and roles table
If I want all the users with role_id of '1' so I can simply do this as
$result = User::whereHas('roles', function ($q){
$q->where('roles.id', 1);
});
but I also want the role name correspond to role_id '1' which is name column of roles table.
Is there any way I can append role name into $result collection.
I think you might want to use map(). The eager loading (with()) is very important though, to prevent the N+1 issue in your query. Without eager loading one additional query would be executed for each user in your result.
$result = App\User::query()
->with([
'roles' => function ($q) {
$q->whereId(1);
}
])
->whereHas('roles', function ($q) {
$q->whereId(1);
})
->get()
->map(function ($user) {
$user['name'] = $user->roles->first()->name;
return $user;
});
You can Eagerload the relationship to get the column you want:
User::whereHas('roles', function ($q){
$q->where('roles.id', 1);
})->with(['roles' => function ($q){
$q->select('name')->where('roles.id', 1);
}])->get();

Filtering eloquent relationship many to many query

I have
Users, Departments, Positions, table.
User belongs to many department
Department has many positions
User belongs to many positions
I want a query that would give a single department with list of users and their position in that department.
$department = DepartmentView::with(['users.positions' => function($query) {
// do something?
}])->where('tag', $tag)
->get();
I also get the department through tag, and not ID. Position table does not have tag column, only department ID.
--
I could make it work by defining static Id, however the problem is I get the department via tag.
public function getDepartmentByTag($tag) {
$departmentId = 1; FOR TESTING PURPOSE, IT WORKS
$department = DepartmentView::with(['users.positions' => function($query) use($departmentId) {
$query->whereHas('department', function($query) use($departmentId) {
$query->where('departmentId', $departmentId);
});
}])->where('tag', $tag)
->get();
}
I want to only get the user position that is in the department
DepartmentView::with(['users.positions' => function($q) use($tag) {
$q->whereHas('department', function($q) use($tag) {
$q->where('tag', $tag);
});
}])
->get();

Laravel query builder subquery separate tables

How do I write this in Laravel Query Builder:
I have a users table that has one Customer with column 'phone'.
a customers table that belongs to User on 'user_id' with column 'mobile'.
I would like to find any customer id that with a phone number what either 'phone' or 'mobile'. Something like this:
select id
from customers
where mobile = '5555555555' or
user_id = (select id
from users
where phone = '5555555555')
I think this is what I need:
$customers = DB::table('customers')
->whereIn('user_id', function ($query) use ($phoneNumber) {
$query->select('id')
->from('users')
->where('users.phone', $phoneNumber);
})
->orWhere('mobile', $phoneNumber)
->pluck('id');

Resources