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();
Related
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
I need to get posts from a category using SQL query in Wordpress, so i use get_resilts but it returns an empty array...please could someone tell me what is wrong in my code...? thanks a lot
$wpdb->get_results("
SELECT ID, post_date
FROM {$wpdb->prefix}posts
LEFT JOIN $wpdb->term_relationships ON
($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON
($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE $wpdb->posts.post_type = 'post'
AND $wpdb->term_taxonomy.taxonomy = 'category'
AND $wpdb->term_taxonomy.term_id = 18
);
Is there a particular need to use an SQL query with $wpdb?
This can be easily be achieved using WordPress functions:
$args = array( 'post_type' => 'post', 'category' => 18 );
$myposts = get_posts( $args );
If using SQL is an absolute requirement you'll want to fix your query.
This is correct:
FROM {$wpdb->prefix}posts
This is not:
LEFT JOIN $wpdb->term_relationships ON
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();
I'm trying to implement search, which will look through custom taxonomy terms.
I have custom type called "product", and custom taxonomy called "type". When I'm using wordpress standard form it works good except the fact, that it doesn't search in custom taxonomy terms.
So, what I need is:
1. Make WP search through "m_type" taxonomy terms
2. It should use "name" of the term, instead of "slug".
I was trying to include additional query vars to make it look through "slugs" at least.
This code:
$wp_query->query['tax_query'] = array(
array(
'taxonomy' => 'm_type',
'field' => 'slug',
'terms' => 'pen'
)
);
Generates the following SQL:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_term_relationships
ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_postmeta ON
(wp_posts.ID = wp_postmeta.post_id) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id
IN (163) ) AND (((wp_posts.post_title LIKE '%pen%') OR (wp_posts.post_content LIKE
'%pen%'))) AND wp_posts.post_type IN ('product') AND (wp_posts.post_status
= 'publish' OR wp_posts.post_author = 1 AND wp_posts.post_status = 'private') AND
(wp_postmeta.meta_key = 'max_price' ) GROUP BY wp_posts.ID
ORDER BY wp_postmeta.meta_value+0 DESC LIMIT 0, 60
So, basically it adds custom taxonomy, search through posts, that have this kind of taxonomy (*wp_term_relationships.term_taxonomy_id IN (163)*) but actually never compares taxonomy term with query string.
Maybe I'm doing all of this wrong?
I am using this sql query to fetch results on the basis of title/taxonomy term/content search where $search is the search parameter and $_REQUEST['post_type'] that I am p
SELECT DISTINCT(ID) FROM
$wpdb->terms AS terms
JOIN
$wpdb->term_taxonomy as termtaxonomy
JOIN
$wpdb->term_relationships AS termrelationship
JOIN
$wpdb->posts AS posts
ON terms.term_id = termtaxonomy.term_id &&
termrelationship.term_taxonomy_id = termtaxonomy.term_taxonomy_id &&
termrelationship.object_id = posts.ID
WHERE terms.name LIKE '%".$search."%' OR posts.post_title LIKE '%".$search."%' OR posts.post_content LIKE '%".$search."%' AND posts.post_type='".$_REQUEST['post_type']
Ok I'm losing on this one. I have an NHibernate query that looks something like this
var subQuery = QueryOver.Of<Lead>()
.Where(x => x.Client == user.Client)
.And(x => x.LeadType == leadType && x.LeadType != LeadTypeEnum.Self)
.Select(Projections.Distinct(Projections.Id()));
I use this
var query = Session.QueryOver<Lead>()
.WithSubquery.WhereProperty(x => x.Id).In(subQuery);
This produces what I need
Where lead.id in (select Id from .......)
However, I need to add another subquery. Easy to do like above, but I need this to produce the following
Where lead.id in (select id from .....)
or lead.id in (select id from .......)
The problem is I'm always getting the following
Where lead.id in (select id from .....)
and lead.id in (select id from .......)
Could someone point me in the correct direction to get the Or please
I'm an NH newbie myself , but you might want to try created a disjunction and adding the conditions to it, then adding the disjunction to the QueryOver Where call.
var disjunction = new Disjunction();
disjunction.Add(subQuery1);
disjunction.Add(subQuery2);
var query = Session.QueryOver<Lead>()
.Where(disjunction);