Count rows in Laravel 4 database - php

Hi I am trying to get the current count of my statement below , but I am getting only the count not the whole result:
$admins = DB::table('users')
->select(DB::raw('count(users.id) as admin_count'))
->where('users_roles.role_id', '=' ,0)
->join('users_roles', 'users.id', '=', 'users_roles.user_id')
->orderBy('first_name', 'asc')
->get();
Could you tell me what I am doing wrong?
Thanks

Just use * in your SELECT clause, and you get entire resultset. Then, $admins is an array, and you can get its count using count method.
$admins = DB::table('users')
->select('users.*')
->join('users_roles', 'users.id', '=', 'users_roles.user_id')
->where('users_roles.role_id', '=' ,0)
->get();
I assume you have users_roles.role_id = 0 for exactly once for a user. There are no multiple entries for role_id = 0 for one user right?
I hope this helps.

Or you can use...
$admins = User::roles()->where('role_id', '=', 0)->count();
If the relations are setup correctly that should work.
Resource: http://laravel.com/docs/eloquent#many-to-many

I am not sure how laravel handles nested selects with the query builder, in plain sql, it would look like this
SELECT users.id, (SELECT COUNT(users.id) FROM users) AS admin_count
FROM users
JOIN users_roles
ON user_roles.id = users.id
WHERE users_roles.role_id = 0
ORDER BY first_name
which I am pretty sure you can just assign to a variable and run it like $admins = DB::query($sql)

Related

How to Find Matching Record Using Left Join in Laravel

I currently have two tables with relationships between the tables: a users table and a comments table.
What I am trying to do is select user.username where comments.location has the same value as user.location. How do I get the currently logged in users comment?
I've tried using Auth::id() within the leftJoin however the error message received is query undefined and also the below statement.
$query = DB::table('recommendation')
->select('users.username')
->leftJoin('users','recommendation.location', '=', 'users.location')
->leftJoin('users','recommendation.user_id', '=' , Auth::id())
->get();
The below statement prints all usernames which have the same location.
$query = DB::table('comments')
->select('users.username')
->leftJoin('users','comments.location', '=', 'users.location')
->get();
Perhaps you need a WHERE clause here:
$query = DB::table('recommendation')
->select('users.username')
->leftJoin('users','recommendation.location', '=', 'users.location')
->where('users.user_id', '=', Auth::id())
->get();

select all columns which are not in another table laravel 5.5

I have two tables - the first one is called 'users' and the second one is called 'buy_courses'.
I am trying to select all users those user_name is not in buy_courses. I tried something like -
$users = DB::table('users')
->rightjoin('buy_courses', 'users.user_name', '=', 'buy_courses.user_name')
->get();
It returns all users, whose user_name is in 'buy_courses', when I am using '<>', then I'm getting all users. What should be the right query?
DB::table("users")->select('*')->whereNotIn('user_name',function($query) {
$query->select('user_name')->from('buy_courses');
})->get();
just join actually is inner join in Laravel so actually maybe also you can try:
DB::table('users')
->join('buy_courses', 'users.user_name', '=', 'buy_courses.user_name')
->get();
Try it using Eloquent:
$courseUserNames = BuyCourses::pluck('user_name')->all();
$users = User::whereNotIn('user_name', $courseUserNames)->select(...)->get();
Or if you prefer using DB query:
$courseUserNames = DB::table('buy_courses')->pluck('user_name')->all();
$users = DB::table('users')->whereNotIn('user_name', $courseUserNames)->select(...)->get();
just replace = with != , use function join
$users = DB::table('users')
->join(
'buy_courses',
function ($join)
{$join->on('users.user_name', '!=', 'buy_courses.user_name');}
)
->get();
You can use SQL's 'NOT IN'.
Example:
mysqli_query($con, "SELECT * FROM users WHERE user_name NOT IN (SELECT user_name FROM buy_courses)");

Convert mysql query into Eloquent laravel query

I am trying to make the following query in laravel:
SELECT a.name AS subname, a.area_id, b.name, u. id, u.lawyer_id,u.active_search,
FROM subarea a
LEFT JOIN user_subarea u ON u.subarea_id = a.id
AND u.user_id = ?
LEFT JOIN branch b ON a.area_id = b.id
The idea is to obtain the subareas and see if the search is activated by the user.
The user_subarea table might have a record that matches the id of the subarea table where the active_search is equal to 0 or 1. If it doesn't exist I would like the query to return null.
While I was able to achieve this in raw SQL when I try the same with eloquent in Laravel I am not returning any value. I have done the following:
$query = DB::table('subarea')
->join('user_subarea', function($join)
{
$value = \Auth::user()->id;
$join->on( 'subarea.id', '=', 'user_subarea.subarea_id')->where('user_subarea.user_id', '=',$value);
})
->leftJoin('branch', 'subarea.area_id', '=', 'branch.id')
->select('branch.name', 'subarea.name as subarea', 'user_subarea.active_search_lawyer', 'user_subarea.id' )
->get();
Any help will be much appreciated.
I found by myself the answer it was just to add a lefjoin in the first join. It is not in the laravel docs but works too.
$query = DB::table('subarea')
->lefjoin('user_subarea', function($join)
{
$value = \Auth::user()->id;
$join->on( 'subarea.id', '=', 'user_subarea.subarea_id')->where('user_subarea.user_id', '=',$value);
})
->leftJoin('branch', 'subarea.area_id', '=', 'branch.id')
->select('branch.name', 'subarea.name as subarea', 'user_subarea.active_search_lawyer', 'user_subarea.id' )
->get();
Try this one, If you get a problem, please comment.
$value = \Auth::user()->id;
$query = DB::table('subarea')
->where('user_subarea.user_id', '=',$value)
->leftJoin('user_subarea', 'subarea.id', '=', 'user_subarea.subarea_id')
->leftJoin('branch', 'subarea.area_id', '=', 'branch.id')
->select('subarea.name AS subname','subarea.area_id', 'branch.name', 'user_subarea.id','user_subarea.lawyer_id','user_subarea.active_search')
->get();

Getting all the users who are not in the particular group in laravel 5.2

I've searched and tried a lot, but unfortunately, I didn't solve my problem. So, I'm posting my question here, please look and suggest me some solution.
I have few tables to manage users like users, profiles, groups, and group_user. Now, I want to retrieve all user name which are not the member of a particular group.
Efforts
$users = DB::table('users')
->join('profiles', 'users.id', '=', 'profiles.user_id')
->join('group_user AS gu', 'gu.user_id', '!=', 'users.id')
->join('groups', 'groups.id', '=', 'gu.group_id')
->where('groups.label', '=', $grouplabel)
->lists(DB::raw("CONCAT_WS(' ',profiles.firstname, profiles.lastname) AS name"),'users.id as id');
I'm executing the query above to get list of users which are not the member of a particular group, but I'm not able to solve it 'til now.
If I change != to = then I get the result of all users who are in the particular group.
Table record and structure in the image.
As, you can see I have 5 users, out of which 3 users having admin group and 2 are not. If I run the query for admin group, then there should be remaining 2 user or if I run query for test group then I should get 5 users.
you don't need to change the join part, all you need to change or add up in your where() section
$users = DB::table('users')
->join('profiles', 'users.id', '=', 'profiles.user_id')
->join('group_user AS gu', 'gu.user_id', '=', 'users.id') // mark it as '='
->join('groups', 'groups.id', '=', 'gu.group_id')
->where('groups.label', '<>', $grouplabel) // change here, see below description
->lists(DB::raw("CONCAT_WS(' ',profiles.firstname, profiles.lastname) AS name"),'users.id as id');
this will ignore the particular group (eg: profile) and will return all other users except this group (profile)
Edited
I just removed the profile section from query, to verify the relationships, once you get the results then we will add up profile section, just run this query
select * from users as u
inner join group_user as gu
on
gu.user_id = u.id
inner join groups as g
on
g.id = gu.group_id where
groups.label <> 'Tester'
Edited 2
$users = DB::table('users')
->join('profiles', 'users.id', '=', 'profiles.user_id')
->join('group_user AS gu', 'gu.user_id', '=', 'users.id')
->join('groups', 'groups.id', '=', 'gu.group_id');
//if users exists in specific group
if($users->where('groups.label', '=', $grouplabel)->count() > 0 ){
$result = $users->where('groups.label', '=', $grouplabel)
->lists(DB::raw("CONCAT_WS(' ',profiles.firstname, profiles.lastname) AS name"),'users.id as id');
} // return all users
else{
$result = $users->lists(DB::raw("CONCAT_WS(' ',profiles.firstname, profiles.lastname) AS name"),'users.id as id');
}

Laravel Eloquent - Select MAX with other columns

I'm trying to select a number of columns along with MAX. The raw query would be something like: SELECT users.id, ..., MAX(ur.rank) AS rank but I cannot figure out how to do it using the query builder supplied by Laravel in Eloquent.
This is my attempt:
$user = User::join('users_ranks AS ur', function($join) {
$join ->on('ur.uid', '=', 'users.id');
})
->where('users.id', '=', 7)
->groupBy('users.id')
->first(['users.id', 'users.username', 'MAX(ur.rank) AS rank']);
I simply cannot figure it out. What I want to achieve is I'm selecting a user where users.id = 7, and I'm wanting to select the MAX rank that's in users_ranks where their users_ranks.uid = users.id.
I was told to avoid sub-queries as when working with large result sets, it can slow things down dramatically.
Can anyone point me in the right direction? Thanks.
I think you should rewrite it like this:
DB::table('users')
->select(['users.id', 'users.username', DB::raw('MAX(ur.rank) AS rank')])
->leftJoin('users_ranks AS ur', 'ur.uid', '=', 'users.id')
->where('users.id', '=', 7)
->groupBy('users.id')
->first();
No sense to use User:: if you use table names later and want to fetch not all of the fields ( 'users.id', 'users.username' ).

Categories