got a select that does 10 query in doctrine (Symfony) - mysql

I got a big query that execute 11 query, I didnt know where the problem is, but found the problem was in a select a did for geo loc, anyone has an idea how to correct that?
It happens only when i use this query SfDoctrinePaginate
Investigating further $q->select("a.longitude") create as much queries..
The problem:
$q->select("a.longitude, a.latitude, (3959 * acos(cos(radians('".$lat."')) * cos(radians(latitude)) * cos(radians(longitude) - radians('".$long."')) + sin(radians('".$lat."')) * sin(radians(latitude)))) AS distance");
the complete model:
public function getListItems($orderby, $budget, $motscles, $userid, $catID, $useDistance = false)
{
$useDistance = true;
// CHANGE ORDER
if(!$orderby){
$orderby = "a.created_at DESC";
}else if($orderby == "price"){
$orderby = "a.price ASC";
}else if($orderby == "date") {
$orderby = "a.created_at DESC";
}else{
$orderby = "a.created_at DESC";
}
// Search Keywords in table
if($motscles){
$searchItem = Doctrine_Core::getTable('csw_Article');
$results = $searchItem->search($motscles);
$ids = array();
foreach ($results as $result) {
$ids[] = $result['id'];
}
if(sizeof($ids) == 0){
$ids[] = 0;
}
}
$q = Doctrine_Core::getTable('csw_Article')
->createQuery("a")
->leftJoin('a.csw_CategorieArticle ca');
$sfContext = sfContext::getInstance()->getUser();
if($useDistance){
$lat = (string)($sfContext->getAttribute('userLat')) ? $sfContext->getAttribute('userLat') : sfConfig::get("app_user_lat");
$long = (string)($sfContext->getAttribute('userLong')) ? $sfContext->getAttribute('userLong') : sfConfig::get("app_user_long");
$radius = 18;
$q->select("a.longitude, a.latitude, (3959 * acos(cos(radians('".$lat."')) * cos(radians(latitude)) * cos(radians(longitude) - radians('".$long."')) + sin(radians('".$lat."')) * sin(radians(latitude)))) AS distance");
$q->having("distance < ?", $radius);
}
if($orderby == "distance") {
$q->orderBy("distance desc");
}
$q->addOrderBy($orderby);
if($catID){
$q->where('ca.categorie_id = ?', $catID);
}
if($budget != 0){
$budget_min = $budget - ($budget * 0.20);
$budget_max = $budget + ($budget * 0.20);
$q->addwhere('a.price > ?',$budget_min)
->addwhere('a.price < ?',$budget_max);
}
if($userid){
$q->WhereIn('a.userid = ?', $userid);
}
if($motscles){
$q->whereIn('a.id', $ids);
}
$q->execute();
return $q;
}

I would change all where by whereIn like:
if($userid){
$q->andWhereIn('a.userid', $userid);
}
if($catID){
$q->andWhereIn('ca.categorie_id', $catID);
}
I think this happens because when you're using the results in the view the paginator cant fetch all records in a row, so for each item has to do the query to get all fields.

I am really not sure why but here what was the problem:
I used
select('a.latitude')
when I should have used...
select('a.*')

Related

How can i paginate this raw query?

I am working on a project in Laravel and using DB facade to run raw queries of sql. In my case I am using DB::select, problem is that pagination method is not working with it and showing this error
Call to a member function paginate() on array
How can I paginate this raw query? here is my code:
$que= DB::select("SELECT * FROM tbl_ourpeople INNER JOIN tbl_ourpeople_category ON
tbl_ourpeople.category = tbl_ourpeople_category.categoryId WHERE tbl_ourpeople.id>1");
return view('view',compact('que'));
Try this:
$query = DB::table('tbl_ourpeople')
->join('tbl_ourpeople_category', 'tbl_ourpeople.category', '=', 'tbl_ourpeople_category.categoryId')
->where('tbl_ourpeople.id', '>', 1)
->paginate(15);
For pure raw query, you may use this way.
$perPage = $request->input("per_page", 10);
$page = $request->input("page", 1);
$skip = $page * $perPage;
if($take < 1) { $take = 1; }
if($skip < 0) { $skip = 0; }
$que = DB::select(DB::raw("SELECT * FROM tbl_ourpeople INNER JOIN tbl_ourpeople_category ON
tbl_ourpeople.category = tbl_ourpeople_category.categoryId WHERE tbl_ourpeople.id>1"));
$totalCount = $que->count();
$results = $que
->take($perPage)
->skip($skip)
->get();
$paginator = new \Illuminate\Pagination\LengthAwarePaginator($results, $totalCount, $take, $page);
return $paginator;

How to use SQL and PHP multiple criteria?

If my original code like this
if (!isset($_GET['page'])) {
$page = 1;
} else {
$page = $_GET['page'];
}
if (!isset($_GET['urut'])) {
$urut = "" ;
} else {
$urut = $_GET['urut'];
}
if($urut == 0){ $urutkan = "id DESC"; };
if($urut == 1){ $urutkan = "harga ASC"; };
if($urut == 2){ $urutkan = "harga DESC"; };
if (!isset($_GET['jenis'])) {
$jenis = [] ;
} else {
$jenis = $_GET['jenis'];
}
if (!isset($_GET['kategori'])) {
$kategori = [] ;
} else {
$kategori = $_GET['kategori'];
}
if (!isset($_GET['wilayah'])) {
$wilayah = [];
} else {
$wilayah = $_GET['wilayah'];
}
$results_per_page = 10;
$sql = "SELECT * FROM item ";
$result = mysqli_query($link, $sql);
$number_of_results = mysqli_num_rows($result);
$number_of_pages = ceil($number_of_results/$results_per_page);
$first_page = ($number_of_results/$number_of_results);
$last_page = $number_of_pages;
$this_page_first_result = ($page-1)*$results_per_page;
$previous = ($page-1);
$next = ($page+1);
$sql='SELECT * FROM item LIMIT ' . $this_page_first_result . ',' . $results_per_page ;
$result = mysqli_query($link, $sql);
What is the right syntax if i want the output like this
$sql='SELECT * FROM item WHERE jenis LIKE '$jenis' AND kategori LIKE '$kategori' AND wilayah LIKE '$wilayah' ORDER BY '$urutkan' LIMIT ' . $this_page_first_result . ',' . $results_per_page ;
Thx for help
...............................................................................................................................................................................................................................................................................................................................
For use multiple criteria into MySQL query you have to use AND operator in query.
Below i give an sample to use criteria with LIKE clause.
SELECT * FROM item WHERE jenis LIKE '%'.$jenis.'%' AND kategori LIKE '%'.$kategori.'%' AND wilayah LIKE '%'.$wilayah.'%' ORDER BY $urutkan
LIMIT $this_page_first_result . ',' . $results_per_page

DataTables warning: table id=seo_editor_product - Invalid JSON response

I use Xampp with MariaDB 10.2.7
I installed a seo module then using json and it shows me the following error.
Error: Uncaught Exception: Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'rows' at line 1<br />Error No: 1064<br />SELECT FOUND_ROWS() as rows in C:\xampp\htdocs\store\system\library\db\mysqli.php:40
<?php
class ModelToolSeoPackageEditor extends Model {
public function __construct($registry) {
parent::__construct($registry);
if (version_compare(VERSION, '3', '>=')) {
$this->url_alias = 'seo_url';
} else {
$this->url_alias = 'url_alias';
}
}
/**
* Create the data output array for the DataTables rows
*
* #param array $columns Column information array
* #param array $data Data from the SQL get
* #return array Formatted data in a row based format
*/
public function data_output ( $columns, $data, $type = '')
{
$out = array();
for ( $i=0, $ien=count($data) ; $i<$ien ; $i++ ) {
$row = array();
for ( $j=0, $jen=count($columns) ; $j<$jen ; $j++ ) {
$column = $columns[$j];
// Is there a formatter?
if($column['db'] == 'related') {
$related = $this->db->query("SELECT pr.related_id, pd.name FROM " . DB_PREFIX . "product_related pr LEFT JOIN " . DB_PREFIX . "product_description pd ON pd.product_id = pr.related_id WHERE pr.product_id='" . $data[$i]['product_id'] . "' AND pd.language_id=" . $this->config->get('config_language_id') . " ORDER BY pd.name")->rows;
$old_related = $old_related_id = array();
foreach ($related as $rel) {
$old_related[] = $rel['name'];
$old_related_id[] = $rel['related_id'];
}
$data[$i]['related']['text'] = implode(', ', $old_related);
$data[$i]['related']['rows'] = $related;
}
if ( isset( $column['formatter'] ) ) {
$row[ $column['dt'] ] = $column['formatter']( $data[$i][ $column['db'] ], $data[$i], $type, $this );
}
else {
$row[ $column['dt'] ] = $data[$i][ $columns[$j]['db'] ];
}
}
$out[] = $row;
}
return $out;
}
/**
* Paging
*
* Construct the LIMIT clause for server-side processing SQL query
*
* #param array $request Data sent to server by DataTables
* #param array $columns Column information array
* #return string SQL limit clause
*/
public function limit ( $request, $columns )
{
$limit = '';
if ( isset($request['start']) && $request['length'] != -1 ) {
$limit = "LIMIT ".intval($request['start']).", ".intval($request['length']);
}
return $limit;
}
/**
* Ordering
*
* Construct the ORDER BY clause for server-side processing SQL query
*
* #param array $request Data sent to server by DataTables
* #param array $columns Column information array
* #return string SQL order by clause
*/
public function order ( $request, $columns, $default )
{
$order = '';
if ( isset($request['order']) && count($request['order']) ) {
$orderBy = array();
$dtColumns = self::pluck( $columns, 'dt' );
for ( $i=0, $ien=count($request['order']) ; $i<$ien ; $i++ ) {
// Convert the column index into the column data property
$columnIdx = intval($request['order'][$i]['column']);
$requestColumn = $request['columns'][$columnIdx];
$columnIdx = array_search( $requestColumn['data'], $dtColumns );
$column = $columns[ $columnIdx ];
if ( $requestColumn['orderable'] == 'true' ) {
$dir = $request['order'][$i]['dir'] === 'asc' ?
'ASC' :
'DESC';
$orderBy[] = '`'.$column['db'].'` '.$dir;
}
}
if(!implode(', ', $orderBy)) return 'ORDER BY ' . $default;
$order = 'ORDER BY '.implode(', ', $orderBy);
}
return $order;
}
/**
* Searching / Filtering
*
* Construct the WHERE clause for server-side processing SQL query.
*
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here performance on large
* databases would be very poor
*
* #param array $request Data sent to server by DataTables
* #param array $columns Column information array
* #param array $bindings Array of values for PDO bindings, used in the
* sql_exec() function
* #return string SQL where clause
*/
public function filter ( $request, $columns, &$bindings )
{
$globalSearch = array();
$columnSearch = array();
$dtColumns = self::pluck( $columns, 'dt' );
if ( isset($request['search']) && $request['search']['value'] != '' ) {
$str = $request['search']['value'];
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
$requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns );
$column = $columns[ $columnIdx ];
if ( $requestColumn['searchable'] == 'true' ) {
$binding = '\'%'. $this->db->escape($str) .'%\'';
$globalSearch[] = "`".$column['db']."` LIKE ".$binding;
}
}
}
// Individual column filtering
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
$requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns );
$column = $columns[ $columnIdx ];
$str = $requestColumn['search']['value'];
if ( $requestColumn['searchable'] == 'true' &&
$str != '' ) {
$binding = '\'%'. $this->db->escape($str) .'%\'';
$columnSearch[] = "`".$column['db']."` LIKE ".$binding;
}
}
// Combine the filters into a single string
$where = '';
if ( count( $globalSearch ) ) {
$where = '('.implode(' OR ', $globalSearch).')';
}
if ( count( $columnSearch ) ) {
$where = $where === '' ?
implode(' AND ', $columnSearch) :
$where .' AND '. implode(' AND ', $columnSearch);
}
if ( $where !== '' ) {
$where = 'WHERE ' . $where;
if($this->filter_language !== false) {
$where .= " AND ";
}
} else if($this->filter_language !== false) {
$where .= " WHERE ";
}
if($this->filter_language !== false) {
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "language` WHERE status = '1'");
foreach ($query->rows as $result) {
if ($result['code'] == $this->config->get('config_language')) $default_lang = $result['language_id'];
}
if ($this->filter_language == $default_lang) {
$where .= " ( language_id = '" . $this->filter_language . "' OR language_id = '0' )";
} else {
$where .= " language_id = '" . $this->filter_language . "'";
}
}
return $where;
}
/**
* Perform the SQL queries needed for an server-side processing requested,
* utilising the helper functions of this class, limit(), order() and
* filter() among others. The returned array is ready to be encoded as JSON
* in response to an SSP request, or can be modified if needed before
* sending back to the client.
*
* #param array $request Data sent to server by DataTables
* #param array $sql_details SQL connection details - see sql_connect()
* #param string $table SQL table to query
* #param string $primaryKey Primary key of the table
* #param array $columns Column information array
* #return array Server-side processing response array
*/
public function simple ( $request, $type, $lang, $store, $columns )
{
$bindings = array();
$extra_select = '';
$extra_where = '';
$primaryKey = $type . '_id';
if (in_array($type, array('product', 'category', 'information'))) {
$select_cols = "`".implode("`, `", self::pluck_fields($columns, 'db'))."`";
$table = '`'.DB_PREFIX . $type . "_description` INNER JOIN `" . DB_PREFIX . $type . "` USING(" . $primaryKey . ")";
$this->filter_language = $lang;
$default_order = 'name';
// #perf: high impact
if (version_compare(VERSION, '3', '>=') || ($this->config->get('mlseo_multistore') && $this->config->get('mlseo_ml_mode'))) {
$extra_select .= ",(SELECT keyword FROM " . DB_PREFIX . $this->url_alias . " u WHERE query = CONCAT('".$type."_id=' , ".$type."_id) AND (language_id = '".(int) $lang."' OR language_id = 0) AND store_id = ".$store." LIMIT 1) AS seo_keyword";
} else if ($this->config->get('mlseo_multistore')) {
$extra_select .= ",(SELECT keyword FROM " . DB_PREFIX . $this->url_alias . " u WHERE query = CONCAT('".$type."_id=' , ".$type."_id) AND store_id = ".$store." LIMIT 1) AS seo_keyword";
} else if ($this->config->get('mlseo_ml_mode')) {
$extra_select .= ",(SELECT keyword FROM " . DB_PREFIX . $this->url_alias . " u WHERE query = CONCAT('".$type."_id=' , ".$type."_id) AND (language_id = '".(int) $lang."' OR language_id = 0) LIMIT 1) AS seo_keyword";
} else {
$extra_select .= ",(SELECT keyword FROM " . DB_PREFIX . $this->url_alias . " WHERE query = CONCAT('".$type."_id=' , ".$type."_id) LIMIT 1) AS seo_keyword";
}
if($type == 'information') {
$default_order = 'title';
}
} elseif (in_array($type, array('manufacturer'))) {
$select_cols = "`".implode("`, `", self::pluck_fields($columns, 'db'))."`";
$this->filter_language = false;
$table = DB_PREFIX . $type . ' m';
$default_order = 'name';
$extra_select = ",(SELECT keyword FROM " . DB_PREFIX . $this->url_alias . " WHERE query = CONCAT('".$type."_id=' , m.".$type."_id) LIMIT 1) AS keyword";
} elseif (in_array($type, array('common', 'special'))) {
$select_cols = "`query`, `keyword`, `".$this->url_alias."_id`";
$primaryKey = $this->url_alias.'_id';
$table = DB_PREFIX . $this->url_alias;
$default_order = 'query';
if ($this->config->get('mlseo_ml_mode')) {
$this->filter_language = $lang;
if ($type == 'common') {
$extra_where = "AND query LIKE 'route=%'";
} elseif ($type == 'special') {
$extra_where = "AND query NOT LIKE 'route=%'
AND query NOT LIKE 'product_id=%'
AND query NOT LIKE 'category_id=%'
AND query NOT LIKE 'information_id=%'
AND query NOT LIKE 'manufacturer_id=%'";
}
} else {
$this->filter_language = false;
if ($type == 'common') {
$extra_where = "AND query LIKE 'route=%'";
} elseif ($type == 'special') {
$extra_where = "AND query NOT LIKE 'route=%'
AND query NOT LIKE 'product_id=%'
AND query NOT LIKE 'category_id=%'
AND query NOT LIKE 'information_id=%'
AND query NOT LIKE 'manufacturer_id=%'";
}
}
$type = 'url_alias';
} elseif ($type == 'absolute') {
$select_cols = "`query`, `redirect`, `url_absolute_id`";
$primaryKey = 'url_absolute_id';
$table = DB_PREFIX . 'url_absolute';
$default_order = 'query';
$type = 'url_absolute';
if ($this->config->get('mlseo_ml_mode')) {
$this->filter_language = $lang;
} else {
$this->filter_language = false;
}
} elseif ($type == 'redirect') {
$select_cols = "`query`, `redirect`, `url_redirect_id`";
$this->filter_language = false;
$primaryKey = 'url_redirect_id';
$table = DB_PREFIX . 'url_redirect';
$default_order = 'query';
$type = 'url_redirect';
} elseif ($type == '404') {
$select_cols = "u.`query`, u.`count`, u.`url_404_id`, (r.query IS NOT NULL) AS has_redirect";
$this->filter_language = false;
$primaryKey = 'url_404_id';
$table = DB_PREFIX . "url_404 u LEFT JOIN " . DB_PREFIX . "url_redirect r ON (u.query = r.query OR REPLACE(u.query, '".HTTP_CATALOG."', '/') = r.query)";
$default_order = 'query';
$type = 'url_404';
} else {
$this->filter_language = false;
$table = DB_PREFIX . $type;
}
// Build the SQL query string from the request
$limit = self::limit( $request, $columns );
$order = self::order( $request, $columns, $default_order );
if ($type == 'url_404') {
$where = self::filter( $request, array(array('db' => 'u`.`query', 'dt' => 0)), $bindings );
} else {
$where = self::filter( $request, $columns, $bindings );
}
if (!$where) {
$where = 'WHERE 1';
}
// Main query to actually get the data
$data = $this->db->query("SELECT SQL_CALC_FOUND_ROWS ". $select_cols . "
" . $extra_select ."
FROM " . $table . ' '
. $where . ' '
. $extra_where . ' '
. $order . ' '
. $limit)->rows;
// Data set length after filtering
$resFilterLength = $this->db->query(
"SELECT FOUND_ROWS() as rows"
)->row;
$recordsFiltered = $resFilterLength['rows'];
// Total data set length
$resTotalLength = $this->db->query(
"SELECT COUNT(`{$primaryKey}`) AS total
FROM $table"
)->row;
$recordsTotal = $resTotalLength['total'];
/*
* Output
*/
return array(
"draw" => intval( $request['draw'] ),
"recordsTotal" => intval( $recordsTotal ),
"recordsFiltered" => intval( $recordsFiltered ),
"data" => self::data_output( $columns, $data, $type )
);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Internal methods
*/
/**
* Throw a fatal error.
*
* This writes out an error message in a JSON string which DataTables will
* see and show to the user in the browser.
*
* #param string $msg Message to send to the client
*/
public function fatal ( $msg )
{
echo json_encode( array(
"error" => $msg
) );
exit(0);
}
/**
* Create a PDO binding key which can be used for escaping variables safely
* when executing a query with sql_exec()
*
* #param array &$a Array of bindings
* #param * $val Value to bind
* #param int $type PDO field type
* #return string Bound key to be used in the SQL where this parameter
* would be used.
*/
public function bind ( &$a, $val, $type )
{
$key = ':binding_'.count( $a );
$a[] = array(
'key' => $key,
'val' => $val,
'type' => $type
);
return $key;
}
/**
* Pull a particular property from each assoc. array in a numeric array,
* returning and array of the property values from each item.
*
* #param array $a Array to get data from
* #param string $prop Property to read
* #return array Array of property values
*/
public function pluck ( $a, $prop )
{
$out = array();
for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) {
$out[] = $a[$i][$prop];
}
return $out;
}
public function pluck_fields ( $a, $prop )
{
$out = array();
for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) {
if($a[$i][$prop] != 'keyword' && $a[$i][$prop] != 'related')
$out[] = $a[$i][$prop];
}
return $out;
}
}

Implementing mysql intersection

I'm trying to do a filter search functionality in codeigniter. I have a table named products and my system has the functionality to filter these products by category and by date. I have a mysql code in mind which looks something like this:
SELECT * from products WHERE product_category='Cloth'
INTERSECT
SELECT * from products WHERE ('insert date logic here')
So it should return records (via id) from the same table named products. However, there's no INTERSECT in mysql so I don't know how to do this. Any help would be greatly appreciated!
This is my code just for the part of the product category
$this->db->limit($limit,$start);
$query = $this->db->query('SELECT * from product_advertised WHERE quantity > 0 AND prodcatid='.$prodcats[0].' LIMIT '.$start.','.$limit);
if(sizeof($prodcats > 1)) {
$query_str = "SELECT * FROM product_advertised WHERE quantity>0 AND ";
$str="";
for($i = 0;$i < sizeof($prodcats);$i++) {
if($i != sizeof($prodcats)-1) {
$str = $str. "prodcatid=".$prodcats[$i]." OR ";
}
else {
$str = $str. "prodcatid=".$prodcats[$i]." LIMIT ".$start.",".$limit;
}
}
$query_str .= $str;
$query = $this->db->query($query_str);
}
if($query->num_rows() > 0) {
foreach($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
Why wouldn't you just use and?
SELECT *
from products
WHERE product_category = 'Cloth' AND
('insert date logic here');

Database Query - Order by two values (Nested Order)

I want to order results by two database values: rating_full followed by rating_count
Currently, Im ordering by the highest rating_full. it works fine.
$sql .= " LEFT JOIN {$wpdb->postmeta} rating ON ({$wpdb->posts}.ID = rating.post_id AND rating.meta_key IN ('rating_full'))";
…
…
$sql = "cast(rating.meta_value as decimal(10,2)) {$order}";
……
The first line of code, part of the SELECT statement, retrieves the rating_full part
The second line of code is the ORDER BY part, which currently just uses the rating_count
As far as I can tell rating.meta_value referred to in the second line of code is the rating_full value
I'm trying to get it to ORDER BY rating_full, rating_count
I'm not sure how to modify the first line so that I can achieve this.
Thanks
FULL CODE:
<?php
// Sorting
add_filter('posts_join', 'directorySortingJoin',10,2);
function directorySortingJoin($join, $query) {
global $wpdb, $aThemeOptions;
if ($query->is_main_query() && !$query->is_admin && ((isset($_GET['dir-search'])) || (isset($query->query_vars["a-dir-item-category"])) || (isset($query->query_vars["a-dir-item-location"])))) {
$sql = "";
// default ordering
$orderby = (isset($aThemeOptions->directory->defaultOrderby)) ? $aThemeOptions->directory->defaultOrderby : 'post_date';
// get from get parameters
if (!empty($_GET['orderby'])) {
$orderby = $_GET['orderby'];
}
if ($orderby == 'rating') {
$sql .= " LEFT JOIN {$wpdb->postmeta} rating ON ({$wpdb->posts}.ID = rating.post_id AND rating.meta_key IN ('rating_full'))";
//$sql .= " LEFT JOIN {$wpdb->postmeta} rating ON (wp_posts.ID = rating.post_id AND rating.meta_key IN ('rating_full')) LEFT JOIN {$wpdb->postmeta} count ON ({$wpdb->posts} = count.post_id AND count.meta_key IN ('rating_count'))";
}
if ($orderby == 'packages') {
directorySaveUserPackagesToDb();
$sql .= " LEFT JOIN {$wpdb->usermeta} packages ON ({$wpdb->posts}.post_author = packages.user_id AND packages.meta_key IN ('dir_package'))";
}
if (isset($aThemeOptions->directory->showFeaturedItemsFirst)) {
$sql .= " LEFT JOIN {$wpdb->postmeta} featured ON ({$wpdb->posts}.ID = featured.post_id AND featured.meta_key IN ('dir_featured'))";
}
$join .= $sql;
//echo $join;
}
return $join;
}
add_filter('posts_orderby', 'directorySortingOrderby',10,2);
function directorySortingOrderby($orderby, $query) {
global $wpdb, $aThemeOptions;
if ($query->is_main_query() && !$query->is_admin && ((isset($_GET['dir-search'])) || (isset($query->query_vars["a-dir-item-category"])) || (isset($query->query_vars["a-dir-item-location"])))) {
$sql = "";
// default ordering
$orderby = (isset($aThemeOptions->directory->defaultOrderby)) ? $aThemeOptions->directory->defaultOrderby : 'post_date';
$order = (isset($aThemeOptions->directory->defaultOrder)) ? $aThemeOptions->directory->defaultOrder : 'DESC';
// get from get parameters
if (!empty($_GET['orderby'])) {
$orderby = $_GET['orderby'];
}
if (!empty($_GET['order'])) {
$order = $_GET['order'];
}
if ($orderby == 'rating') {
if (isset($aThemeOptions->directory->showFeaturedItemsFirst)) {
$sql = "featured.meta_value DESC, convert(rating.meta_value, decimal) {$order}";
} else {
//$sql = "convert(rating.meta_value, decimal) {$order}";
$sql = "cast(rating.meta_value as decimal(10,2)) {$order}";
//$sql = "cast(rating.meta_value as decimal(10,2)) {$order}, count.meta_value {$order}";
}
} else if ($orderby == 'packages') {
if (isset($aThemeOptions->directory->showFeaturedItemsFirst)) {
$sql = "featured.meta_value DESC, packages.meta_value {$order}";
} else {
$sql = "packages.meta_value {$order}";
}
} else {
if (isset($aThemeOptions->directory->showFeaturedItemsFirst)) {
$sql = "featured.meta_value DESC, {$wpdb->posts}.{$orderby} {$order}";
}
}
$orderby = $sql;
//echo $orderby;
}
return $orderby;
}
// Save directory packages for sorting
function directorySaveUserPackagesToDb() {
$users = get_users();
// capabilities list
$roles = array(
'administrator' => 10,
'directory_5' => 9,
'directory_4' => 8,
'directory_3' => 7,
'directory_2' => 6,
'directory_1' => 5,
'editor' => 4,
'author' => 3,
'contributor' => 2,
'subscriber' => 1
);
foreach ($users as $user) {
if (isset($user->roles[0])) {
if (array_key_exists($user->roles[0], $roles)) {
update_user_meta($user->ID, 'dir_package', $roles[$user->roles[0]]);
} else {
update_user_meta($user->ID, 'dir_package', 0);
}
}
}
}
The MySQL documentation for ORDER BY should be helpful here, particularly the last paragraph on sorting multiple columns.
Your ORDER BY should be something like
ORDER BY rating_full DESC, rating_count DESC