SQL Postgre to show 1 data if get same some multiple data and how to implement to laravel query - sql

i want to ask about sql in postgresql, i got data from join with 3 table, i got the result but i got multiple data like this image
result
and here my sql code in postgresql
select users.* from users inner join model_has_roles on model_has_roles.model_id = users.id
left join roles on roles.id = model_has_roles.role_id where roles.name not in ('job-seeker') order by users.name asc
how to fix this query where i got the multiple data only 1 data to show.
and i want this sql to implement to laravel query and here my code now
public function getAccountList(){
$req = app(Request::class);
// $getAccount = User::query();
$getAccount = User::join('model_has_roles', function($join) {
$join->on('users.id', '=', 'model_has_roles.model_id');
})->leftJoin('roles', function($join){
$join->on('model_has_roles.role_id', '=', 'roles.id');
});
$getAccount->whereNotIn('roles.name', ['job-seeker']);
if ($q = $req->query('q')) {
$searchTerm = trim(strtolower($q));
$getAccount->whereRaw(
'LOWER(users.name) like (?) or LOWER(users.email) like (?)',
["%{$searchTerm}%", "%{$searchTerm}%"]
);
}
// $getAccount->get()->unique('name');
$getAccount->select(['users.*']);
$paginator = $this->pagination($getAccount);
return $this->paginate($paginator, new UserTransformer);
}
how to fix the query only 1 data to show not the multiple same data. thank you for helping me. God Bless You

use distinct()
$data = DB::table('test')->[your query builder]->distinct()->get();
Laravel Query Builder Docs
Just change a bit to make it related to your query builder

Related

Add multiple rows in Laravel DB Query (for migrating WordPress usermeta table into new Laravel table)

I'm migrating Users from WordPress to Laravel. I want to join the users and user_meta tables. Then I will import into a new table.
In my user_meta table I have multiple rows assigned to the user_id. How do I import multiple rows with their own unique identifier.
Eg.
umeta_id = 1, user_id = 1, meta_key = first_name, meta_value = Bob
umeta_id = 2, user_id = 1, meta_key = last_name, meta_value = Builder
In the above example, I'd like to add first_name and last_name to the query output.
Then import into a new column in the Laravel DB (and stop using the user_meta reference table approach WordPress uses).
Here is my current query code and the output I get:
$wp_users = DB::connection('wordpress_db')
// ->select(DB::raw('um.meta_value as first_name'))
->select('um.meta_value as first_name')
->table('wp_users')
->leftJoin('wp_usermeta as um', function ($q) {
$q->on('um.user_id', '=', 'wp_users.id')
->where('um.meta_key', '=', "first_name");
})
->orderBy('wp_users.id');
and if i dump the output:
+"ID": 1
+"user_login": "123"
+"user_pass": "123"
+"user_nicename": "123"
+"user_email": "b#x"
+"user_url": "https://x"
+"user_registered": "2016-1-1 13:47:32"
+"user_activation_key": ""
+"user_status": 0
+"display_name": "Bobby Builds"
+"umeta_id": 222
+"user_id": 1
+"meta_key": "first_name"
+"meta_value": "Bob"
Rather than meta_value and meta_key I just want 'first_name' => 'bob' and then also the ability to do this for multiple values in the user_meta reference table
If I was writing RAW sql then I think I would approach this by having a left_join per value I want to get. I would then create an alias like
SELECT um1.meta_value as first_name
SELECT um2.meta_value as last_name
LEFTJOIN wp_usermeta as um1
LEFTJOIN wp_usermeta as um2
I've noodled around without luck - any ideas appreciated.
Thanks!
I've written about some of the processes involved here for further reference: http://raison.co/migrating-wordpress-users-to-laravel/
I did this in the end by using select to choose all columns from wp_users and then selectively adding the new joins.
See the code fixed code below:
$wp_users = DB::connection('wp_db')
->table('wp_users')
->leftJoin('wp_usermeta as um', function ($q) {
$q->on('um.user_id', '=', 'wp_users.id')
->where('um.meta_key', '=', "wbp_user_mob_phone");
})
->leftJoin('wp_usermeta as um2', function ($q) {
$q->on('um2.user_id', '=', 'wp_users.id')
->where('um2.meta_key', '=', "first_name");
})
->select('wp_users.*', 'um.meta_value as wbp_user_mob_phone', 'um2.meta_value as first_name')
->orderBy('wp_users.id');

I need to get Subject name with total number of Book

I have a SQL Query which I want to convert in Linq or want to show data
as pictured here
Here is the query:
select sae_subcategorymaster.subject, count(sae_tblbookdetail.title)
from sae_tblbookdetail inner join sae_subcategorymaster
on sae_subcategorymaster.subject=sae_tblbookdetail.subject
group by sae_subcategorymaster.subject
What is a simple way to do this?
Grouping is supported in LinqEF. Provided you have your entities related. (Books have a reference to their subcategory.)
var totals = context.Books
.GroupBy(book => book.SubCategory.Subject)
.Select(group => new
{
Subject = group.Key,
BookCount = group.Count()
}).ToList();

Write Nested Select Query in Laravel 5.3

How do I write a complex query in Laravel 5.3? I am trying but not getting the result I expect.
Query
SELECT * FROM (SELECT posts.post_id
FROM posts
WHERE ((posts.user_id = 1 AND posts.user_type = 'user')
OR (posts.user_id IN (1) AND posts.user_type = 'page'))) posts
WHERE posts.post_id > '0' ORDER BY posts.post_id DESC
Please help me write this using Laravel Query Builder.
#Punit Gajjar has provided one solution, but that's not quite what your question was given the terms Query Builder. His solution will work, but half it it doesn't make use of the query builder (it's just a copy/paste and throwing your SQL into a raw query, which is essentially exactly the same thing as you had before) and therefore I feel it's necessary to provide you with an additional option:
Post::where('post_id', '>', 0)
->where(function($query) {
$query->where(function($subquery) {
$subquery->where('user_id', 1)->where('user_type', 'user');
})->orWhere(function($subquery) {
$subquery->whereIn('user_id', [1])->where('user_type', 'page');
});
})
->orderBy('post_id', 'DESC')
->get();
I've kept variables names short just for readability purposes, but the argument in the anonymous functions ($query and $subquery) are the query builder instances.
Here is your answer .
$MyQuery = DB::table(DB::Raw("(SELECT
posts.post_id
FROM
posts
WHERE
(
(
posts.user_id = 1
AND posts.user_type = 'user'
)
OR
(
posts.user_id IN (1)
AND posts.user_type = 'page'
)
)
)"))
->where('posts.post_id','>',"0")->orderBy("posts.post_id" , "DESC")->get();
Try printing query once using ->toSql() like this
echo $MyQuery = DB::table(DB::Raw("(SELECT
posts.post_id
FROM
posts
WHERE((
posts.user_id = 1
AND posts.user_type = 'user'
)
OR(
posts.user_id IN (1)
AND posts.user_type = 'page'
)))"))
->where('posts.post_id','>',"0")->orderBy("posts.post_id" , "DESC")->toSql();
die();

OrderBy count appearing in the wrong order in Eloquent Query Builder (Laravel 4)

I have the following query:
public static function artists_most_popular() {
$artists_most_popular = DB::table('artists')
->join('fanartists', 'artists.id', '=', 'fanartists.artist_id')
->orderBy(DB::raw('count(*)', 'DESC'))
->groupBy('artists.id')
->take(50)
->get();
return $artists_most_popular;
}
As you can see from the query, I would like the data to appear in descending order by count of the times the artist_id appears in the fanartists table. However, when I use "foreach" and output this data, it appears in ascending order. Any ideas for why this is happening? I used the following query in SQL Pro, and it works as it should:
select *, COUNT(*)
from artists
join fanartists on artists.id = fanartists.artist_id
group by artists.id
order by (COUNT(*)) desc
I have changed the query little bit. Hopefully this will work.
$artists_most_popular = DB::table('artists')
->join('fanartists', 'artists.id', '=', 'fanartists.artist_id')
->select(DB::raw('artists.*, fanartists.*, COUNT(*) AS total_artists'))
->orderBy('total_artists', 'DESC'))
->groupBy('artists.id')
->take(50)
->get();
Also if you want your Artists collection to be returned (this pretends your Artists Model is called Artists), and to further enhance Anam's response, you could do something like:
$artists_most_popular = Artists::join('fanartists', 'artists.id', '=', 'fanartists.artist_id')
->select(DB::raw('artists.*, fanartists.*, COUNT(*) AS total_artists'))
->orderBy('total_artists', 'DESC'))
->groupBy('artists.id')
->take(50)
->get();

Nested select not working in NHibernate.Linq

I want to load the list of users and their roles, with this query:
var q = from u in session.Linq<User>()
select new
{
u.Name,
u.Password,
Roles = from r in u.Roles
select new { r.Code, r.Name }
};
But this query is not working.
Produce the following error: "The method 'Select' is not implemented."
¿The message suggest that NHibernate.Linq not support nested selects?
I want to know if this is certain or exist other way to do this?
PD: please excuse my bad english.
Current implementation of Linq provider is based on CriteriaApi and that why it can create only simple queries