Apply distinct on join query with CodeIgniter Query Builder - php

I am trying to make a query with codeigniters Query Builder
$this->db->select('*')
->from('users')
->join('user_to_group', 'users.id=user_to_group.user_id')
->where('user_to_group.group_id !=', $group->id);
Here in above code I'm trying to fetch records of users which are not in provided group. This query is working fine at the stage but sometimes it returns same record multiple times as a user can be part of multiple groups. So to overcome this problem I want to apply distinct to this query.
But I don't find the correct way to do it.
Please help..

You need to add group_by in query.
Write your query as below:-
$this->db->select('*')
->from('users')
->join('user_to_group', 'users.id=user_to_group.user_id')
->where('user_to_group.group_id !=', $group->id)
->group_by('users.id'); // add this line

Note : this query will work in only case if you use "user_to_group" table as multiple relation table mean user and group both tables id you used in this third table name "user_to_group".
Use group by if you need unique record on base of group_id
Try this :
$this->db->select('*')
->from('users')
->join('user_to_group', 'users.id=user_to_group.user_id')
->where('user_to_group.group_id !=', $group->id)
->group_by("user_to_group.group_id");
Because you will get multiple record when user is part of multiple group so you will use this to get groups unique records user vise or you will apply both group_id and user_id in group_by to get it unique from both field.

Related

CodeIgniter count within query as extra column

I am having a query in CodeIgniter which is working fine.
Now I would like to have an additional COUNT inside per output line, this data is shown inside a table.
I want to see per line how much times the user has requested a device.
I don't want the output to be grouped, I want one column per row that says this user has 3 requests, so in this case 3 rows from the same user, having a different deviceRequest, with 3 times in this column count being 3.
PS: I am quite new to this, info about your solution would be appreciated.
Query:
$datatables->select('
deviceRequestID,
deviceRequestStatuses.deviceRequestStatusShortname,
users.userEmail,
users.userID,
users.userName,
users.userSurname,
deviceRequestComments,
deviceRequests.createdAt,
deviceRequests.updatedAt,
rooms.roomName,
hotspots.hotspotName,
hotspots.hotspotAddress,
hotspots.hotspotCity,
hotspots.hotspotZIP,
DATEDIFF(CURDATE(), deviceRequests.createdAt) AS daysDifference,
')
->join('users', 'deviceRequests.userID=users.userID', 'left')
->join('deviceRequestStatuses', 'deviceRequests.deviceRequestStatusID=deviceRequestStatuses.deviceRequestStatusID')
->join('rooms', 'users.roomID=rooms.roomID', 'left')
->join('hotspots', 'rooms.hotspotID=hotspots.hotspotID', 'left')
->from('deviceRequests');
I added this extra query line inside the select part of the query above, it does exactly what I need.
(SELECT count(userID) FROM deviceRequests WHERE userID = users.userID) AS deviceCount

Running a SQL delete query in Laravel

I have an SQL query:
DELETE n1
FROM satellites n1
, satellites n2
WHERE n1.id < n2.id
AND n1.norad_cat_id = n2.norad_cat_id
What this query does is delete rows that have the same norad_cat_id and only leave one with the highest id. I don't know if my SQL query is correct, but I will have to see.
I am a bit stuck when it comes to running raw SQL queries in Laravel. From this documentation (https://laravel.com/docs/5.4/database#running-queries) you can see that you have a few options to run the query:
DB::update('SQL QUERY HERE');
DB::delete('SQL QUERY HERE');
DB::statement('SQL QUERY HERE');
DB::select( DB::raw('SQL QUERY HERE'));
In my case I am trying to delete duplicate rows while only leaving the one with the highest id. What Laravel DB statement do I run to achieve the results I want or does it matter at all?
EDIT: SQL query for #MasudMiah
delete satellites
from satellites
inner join (
select max(id) as lastId, norad_cat_id
from satellites
group by norad_cat_id
having count(*) > 1) duplic on duplic.norad_cat_id = satellites.norad_cat_id
where satellites.norad_cat_id < duplic.lastId;
If you want to run directly your DELETE SQL query, you can use:
$nrd = DB::delete('SQL QUERY HERE');
It returns the number of affected /deleted rows.
See this page:
http://coursesweb.net/laravel/working-mysql-database#anc_rsq
I am afraid your query is not right though. but let me show you some :
DELETE FROM table1 WHERE user_id='$your_provided_value';
DELETE FROM table2 WHERE user_id='$your_provided_value';
Now using query builder for laravel :
DB::table('table_name')
->where('id',$your_provided_value)
->delete();
One thing I would like to mention to set multiple conditions like id = 1 AND gender = 'male' you need to something like that
DB::table('table_name')->where('id',1)
->where('gendar','male')
->delete();
Now by eloquent :
User:where('id', 1)->delete();
here User is your model for the users table. Hope you are getting some basics.
by visiting below link you get the idea of using eloquent.
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel

Laravel Querybuilder join on LIKE

I am attempting to join two tables using the Laravel's query builder however I seem to be having an issue getting the desired result using the query builder, I can however get it quite simply using a raw SQL statement. I simply want to return all mod rows that have the corrosponding value in the tag column in the tags table.
Schema
--------------
mods
--------------
id - int - (primary key)
name - varchar
--------------
tags
--------------
id - int
modid - int - (primary key of its parent mod)
tag - varchar
Working SQL query
SELECT * FROM mod JOIN tags ON tags.tag LIKE '%FPS%'
Query Builder
DB::table('mods')
->join('tags', function ($join) {
$join->on('tags.tag', 'like', '%FPS%');
})
->get();
Currently this is telling me: Unknown column '%FPS%' in 'on clause' but I am unsure how else to structure this. I intend on adding more orOn clauses as well as I will want to get results on multiple tags but firstly I just want to get a single tag working.
Appreciate any help.
SELECT * FROM mod JOIN tags ON tags.tag LIKE '%FPS%'
Your query builder is refusing to generate this query because it's nonsense!
To work correctly, a JOIN clause needs to compare two columns for equality -- one column on each side of the join table. A JOIN clause that doesn't do this is functionally "downgraded" to a WHERE clause. In the case of this query, the two tables end up cross joined.
What you probably want is:
SELECT * FROM mod
JOIN tags ON tags.modid = mod.id
WHERE tags.tag LIKE '%FPS%';
$join->on('tags.tag', 'like', '%FPS%');
Try by replacing
$join->where('tags.tag', 'like', '%FPS%');
This because the on method waiting a name of a field not a query value if you want it to deal with it in this way, you should use DB::raw('%FPS%').
Maybe you are trying to do something like the following:
DB::table('mods')
->select(DB::raw('mods.id as modid, mods.name, tags.id as tagid, tags.tag'))
->join('tags', function ($join) {
$join->on('tags.modid', '=', 'mods.id');
})
->where('tags.tag', 'like', '%FPS%')
->get();
If you want to see what is run in the database use
dd(DB::getQueryLog())
to see what queries were run.
Try this
Thank you

Getting the 4 last values from the MySQL table

In my MySQL table I have a column called emails. How can I get the last 4 values from that column using Doctrine?
You have to write this query in code, if you want to do it with query builder,
you can run this code example:
$query = $em->getRepository('TableRepository')
->createQueryBuilder('t')
->orderBy('t.id', 'DESC')
->getQuery()
->setMaxResult(4);

Laravel Eloquent Query to return count of grouped objects

I am working with laravel 5.1 and can't get this query to work. I have a places table, with a column county. I want to group by county and count how many of each country are in the table. I have a Place model for the places table but cannot figure out the query builder for this one.
A query that works is:
select county, count(*) from places group by county
Thanks in advance.
You may try this (Add a use statement for DB or use \DB):
$result = DB::table('places')
->select('county', DB::raw('count(*) as total'))
->groupBy('county')
->get();
Just from the top of my head does something like this work:
User::where('county')->count();

Categories