How to get posts from a category using SQL query in Wordpress - sql

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

Related

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

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 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();

Wordpress Custom Taxonomy Search

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']

yii cdbcriteria: complex joins

I recently started a project using Yii and I'm trying to get used to the query builder. Now, I want to make a query using joins and access the joining tables' data in the query but I haven't been able to get the following to work:
My (simplified) db-tables:
customer(#id, name)
employee(#id, name)
customer_employee(#customerid, #employeeid)
accounting(#id, customerid, started_date, finished_date, month, year)
many-to-many relation between customer and employee
one-to-many relation between customer and accounting
I want to execute the following query, which would select all the customers associated with a certain employee and display their accounting status (started_date & finished_date) if applicable (otherwise null).
The following query works perfectly, it's just that I can't get it to work with the cdbcriteria and Yii query builder: (also, hardcoded id is just for this example)
SELECT name, started_date, finished_date
FROM customer
RIGHT JOIN customer_employee ON customer.id=customer_employee.customerid
LEFT JOIN accounting ON customer.id=accounting.customerid
WHERE customer_employee.employeeid=2';
Please help!
1.
createCommand
Yii::app()->db->createCommand()
->select('name, started_date, finished_date')
->from('customer c')
->rightJoin('customer_employee ce', 'c.id=ce.customerid')
->leftJoin('accounting a', 'c.id=a.customerid')
->where('ce.employeeid=:id', array(':id'=>2))
->queryRow();
2.
CdbCriteria
$criteria = new CDbCriteria;
$criteria->select = 'name, started_date, finished_date';
$criteria->join = 'RIGHT JOIN customer_employee ON customer.id=customer_employee.customerid ';
$criteria->join .= 'LEFT JOIN accounting ON customer.id=accounting.customerid';
$criteria->condition = 'customer_employee.employeeid=:id';
$criteria->params = array(':id'=>2);
$customers = Customers::model()->find($criteria);
*.
don't forget the rules: http://www.yiiframework.com/doc/guide/1.1/en/database.arr
I didn't tested your SQLs, but if worked for you, these should, also work in Yii.
$criteria = new CDbCriteria();
$criteria->select = "name, started_date, finished_date";
$criteria->join = "RIGHT JOIN customer_employee ON customer.id=customer_employee.customerid LEFT JOIN accounting ON customer.id=accounting.customerid";
$criteria->condition = "customer_employee.employeeid=2";
$models = Customer::model()->findAll($criteria);
This is how to get data with command for table customer_employee
foreach($model as $value)
{
}
A bit late in the day but see this post on my blog which addresses both parts of this difficult sub-query style SQL.
Firstly, to build a Search that relies on attributes from other models
Secondly, to use related models simply without using the full Yii AR model
http://sudwebdesign.com/yii-parameterising-a-sub-select-in-sql-builder/932
I have not run it but some thing like the following is what you need
$criteria = new CDbCriteria();
$criteria->select = "name, started_date, finished_date";
$criteria->join = "RIGHT JOIN customer_employee ON customer.id=customer_employee.customerid LEFT JOIN accounting ON customer.id=accounting.customerid";
$criteria->condition = "customer_employee.employeeid=2";
$models = Customer::model()->findAll($criteria);

Yii order by another table CActiveDataProvider

I am a bit stumped on this. Basically I have two tables:
Page:
id
name
Points:
id-
pageid
points
I am looking to get the records from the Page table, and sort it by the amount of points it has in the Points table (the points field)
Currently I have:
$dataProvider=new CActiveDataProvider('Page',array(
'criteria'=>array(
'condition'=>"active = 1 AND userid IN (".$ids.")",
'order'=>"???",
),
'pagination'=>array(
'pageSize'=>30,
),
));
I just don't know how to sort it by the Points table value for the relevant record
I have set up a relation for the Page/Points tables like so:
(in the Page model)
'pagepoints' => array(self::HAS_ONE, 'Points', 'pageid'),
Thanks
You need to do two things:
Add the pagepoints relation to the with part of the query criteria
Reference the column you want to sort by in the order part of the criteria
I 've marked the lines where this happens in the code below:
$dataProvider = new CActiveDataProvider('Page', array(
'criteria'=>array(
'with' => array('pagepoints'), // #1
'condition' => 'active = 1 AND userid IN ('.$ids.')',
'order' => 'pagepoints.points', // #2
),
'pagination'=>array(
'pageSize'=>30,
),
));
What you need to know to understand how this works is that when Yii builds the SQL query (which is a LEFT OUTER JOIN to the Points table), it uses the name you gave to the relation in the Page model (you give the definition for this, it's pagepoints) to alias the joined table. In other words, the query looks like:
SELECT ... FROM Page ... LEFT OUTER JOIN `Points` `pagepoints` ...
It follows that the correct specification for the sort order is pagepoints.points: pagepoints is the table alias, and points is the column in that table.
Try the following
$dataProvider=new CActiveDataProvider('Page',array(
'criteria'=>array(
'with'=>array('pagepoints'),
'condition'=>"active = 1 AND userid IN (".$ids.")",
'order'=>"t.points DESC",
),
'pagination'=>array(
'pageSize'=>30,
),
));
this is the sql you want to generate:
select * from page inner join points
on page.id = points.page_id order by
points.points desc