Paginate do not sort DESC - php

I can't display Agreements with agreement_number less than 7 and order it by agreement_number DESC.
I have read Pagination CakePHP Cook Book and can't find where my code is wrong. It display only less than 7, but always ASC. I have found similar question here, [that works],(CakePHP paginate and order by) and do not know why. Agreement.agreement_number is int(4).
$this->Agreement->recursive = 0;
$agreements = $this->Paginator->paginate('Agreement', array(
'Agreement.agreement_number <' => '7'
), array(
'Agreement.agreement_number' => 'desc'
)
);
$this->set('agreements', $agreements);
}
Exact cake version is 2.5.2.

... Where did you read that that was the correct syntax?
The paginate function's third parameter is for sorting (and I mean, within the table... with those down and up arrows).
List of allowed fields for ordering. This allows you to prevent
ordering on non-indexed, or undesirable columns.
You have the exact link used for documentation of the API, but you don't seem to be following it (like, from here and here)
$this->Paginator->settings = array(
'Agreement' => array(
'order' => array('Agreement.agreement_number' => 'desc')
)
);
$agreements = $this->Paginator->paginate('Agreement', array(
'Agreement.agreement_number <' => '7'));

Related

Wordpress sort by meta values

I have an issue I am trying to solve right now and having an issue finding a way to do it properly.
I have a college lecture series I need to sort I can sort it by a meta field for year just fine. But when I get to sorting by semester it sorts it in alphabetical and so it ends up sorting by Winter,Spring,Fall or Fall,Spring,Winter depending on if I tell it ASC or DESC.
I need to figure out how to do order this in the right order preferably without adding another field to the posts for sort priority
Query args currently written as follows which is obviously a bit messy.
$args = array(
'post_type' => 'mcm_geri-ed',
'posts_per_page' => $posts_per_page,
'meta_query' => array(
'semester' => array(
'key' => 'semester',
),
'year' => array(
'key' => 'year'
)
),
'orderby' => array(
'year' => 'DESC',
'semester' => array(
'value' => 'date'
)
),
'paged' => $paged
);
I don't think there is a way to do this with WP_Query directly. How about using posts_orderby and manipulating the ORDER-part of the SQL to be something like meta_year DESC, meta_semester = 'Spring' DESC, meta_semester = 'Fall' DESC. Look at the generated SQL to see what names you should use for meta_year and meta_semester (or trimester, really).
This isn't as effective as changing semester to a numerical value and adding the name while outputting, but it will work.
This is what I ultimately did. It was something different than what was suggested but using the filter suggested to get the result. The if statement has a couple of other caveats added to it due to the way I've built a sorting system for the page template. I also wrote this in a test environment hence the different post type from the original code.
// Custom Orderby filter to return the correct order for semester values.
add_filter('posts_orderby', 'orderby_pages_callback', 10, 2);
function orderby_pages_callback($orderby_statement, $wp_query) {
//Making sure this only happens when it needs to. Which is the right post type and if it isn't getting sorted by other functions.
if ($wp_query->get("post_type") === "test_semester" && !is_admin() && !isset($_GET['order']) && !isset($_GET['sort'])) {
return "CAST(mt1.meta_value AS CHAR) DESC, wp_postmeta.meta_value = 'Fall' DESC, wp_postmeta.meta_value = 'Winter' DESC, wp_postmeta.meta_value = 'Spring' DESC,wp_postmeta.meta_value = 'Summer' DESC";
} else {
//return your regularly scheduled programming
return $orderby_statement;
}
}

data escaping remove for specific filed in cakephp

I am using subquery for id field.
$db = $this->AccountRequest->getDataSource();
$subQuery = $db->buildStatement(
array(
'fields' => array('MAX(id)'),
'table' => $db->fullTableName($this->AccountRequest),
'alias' => 'MaxRecord',
'limit' => null,
'offset' => null,
'order' => null,
'group' => array("user_id")
),
$this->AccountRequest
);
$searching_parameters = array(
#"AccountRequest.id IN " => "(SELECT MAX( id ) FROM `account_requests` GROUP BY user_id)"
"AccountRequest.id IN " => "(".$subQuery.")"
);
$this->Paginator->settings = array(
#'fields' => array('AccountRequest.*'),
'conditions' => $searching_parameters,
'limit' => $limit,
'page' => $page_number,
#'group' => array("AccountRequest.user_id"),
'order' => array(
'AccountRequest.id' => 'DESC'
)
);
$data = $this->Paginator->paginate('AccountRequest');
This structure is producing a query is:
SELECT
`AccountRequest`.`id`,
`AccountRequest`.`user_id`,
`AccountRequest`.`email`,
`AccountRequest`.`emailchange`,
`AccountRequest`.`email_previously_changed`,
`AccountRequest`.`first_name`,
`AccountRequest`.`first_namechange`,
`AccountRequest`.`f_name_previously_changed`,
`AccountRequest`.`last_name`,
`AccountRequest`.`last_namechange`,
`AccountRequest`.`l_name_previously_changed`,
`AccountRequest`.`reason`,
`AccountRequest`.`status`,
`AccountRequest`.`created`,
`AccountRequest`.`modified`
FROM
`syonserv_meetauto`.`account_requests` AS `AccountRequest`
WHERE
`AccountRequest`.`id` IN '(SELECT MAX(id) FROM `syonserv_meetauto`.`account_requests` AS `MaxRecord` WHERE 1 = 1 GROUP BY user_id)'
ORDER BY
`AccountRequest`.`id` DESC
LIMIT 25
In the subquery, its add an extra single quote so it's producing an error.
So, How can I remove these single quotes from this subquery?
Thanks
What are you trying to achieve with the sub query?
The MAX(id) just means it will pull the id with the largest value AKA the most recent insert. The sub query is completely redundant when you can just ORDER BY id DESC.
using MAX() will return only one record, if this is what you want to achieve you can replicate by adding LIMIT 1
If the sub query is just an example and is meant to be from another table I would just run the query that gets the most recent id before running the main query. Getting the last inserted id in a separate query is very quick and I cant see much of a performance loss. I think it will result in cleaner code that`s easier to follow to.
edit 1: From the comments it sounds like all your trying to get is a particular users latest account_requests.
You dont need the sub query at all. My query below will get the most recent account record for the user id you choose.
$this->Paginator->settings = array(
'fields' => array('AccountRequest.*'),
'conditions' => array(
'AccountRequest.user_id' => $userID // you need to set the $userID
)
'page' => $page_number,
'order' => array(
'AccountRequest.id DESC' //shows most recent first
),
'limit' => 1 // set however many you want the maximum to be
);
The other thing you cold be meaning is to get multiple entries from multiple users and display them in order of user first and then the order of recent to old for that user. MYSQL lets you order by more than one field, in that case try:
$this->Paginator->settings = array(
'conditions' => array(
'AccountRequest.user_id' => $userID // you need to set the $userID
)
'page' => $page_number,
'order' => array(
'AccountRequest.user_id', //order by the users first
'AccountRequest.id DESC' //then order there requests by recent to old
)
);
If the example data you have added into the question is irrelevant and you are only concerned about how to do nested subqueries it has already been answered here
CakePHP nesting two select queries
However I still think based on the data in the question you can avoid using a nested query.

CakePHP order not working

Hi i am using CakePHP version - 2.5.5.
I have a table name chat_ategory_mages I want to get Average number of Frequency Order by Descending. Know about the Frequency please check - How to get Average hits between current date to posted date in MySQL?
chat_ategory_mages
id chat_category_id hits created
------------------------------------------------
1 5 10 2014-11-07 11:07:57
2 5 8 2014-11-10 05:10:20
3 5 70 2014-10-04 08:04:22
Code
$order=array('Frequency' => 'DESC');
$fields=array(
'ChatCategoryImage.id',
'ChatCategoryImage.chat_category_id',
'ChatCategoryImage.created',
'ChatCategoryImage.hits',
'hits/(DATEDIFF(NOW(),created)) AS Frequency',
);
QUERY-1
$rndQry=$this->ChatCategoryImage->find('all',array('conditions'=>array('ChatCategoryImage.chat_category_id'=>$cetegory_id), 'fields'=>$fields, 'order'=>$order, 'limit'=>10));
pr($rndQry); //WORKING FINE
QUERY-2
//THIS IS NOT WORKING
$this->Paginator->settings = array(
'conditions'=>array('ChatCategoryImage.chat_category_id'=>$cetegory_id),
'fields'=>$fields,
'limit' => 10,
'order' => $order,
);
$getCategoryImages = $this->Paginator->paginate('ChatCategoryImage');
pr($getCategoryImages); //NOT WORKING
Above table if i write simple cakephp query the order is working fine but when i am using cakephp pagination it is not working. If i am using $order=array('hits' => 'DESC'); this its woring perfect. Showing result 70,10,8 consistently but when i am adding Frequency it the result not coming the descending order.
Mysql Query
QUERY-1 :
SELECT ChatCategoryImage.id, ChatCategoryImage.chat_category_id, ChatCategoryImage.hits, ChatCategoryImage.created, hits/(DATEDIFF(NOW(),created)) AS Frequency, FROM myshowcam.chat_category_images AS ChatCategoryImage WHERE ChatCategoryImage.chat_category_id = 5 ORDER BY Frequency DESC LIMIT 10
QUERY-2 :
SELECT ChatCategoryImage.id, ChatCategoryImage.chat_category_id, ChatCategoryImage.hits, ChatCategoryImage.created, hits/(DATEDIFF(NOW(),created)) AS Frequency, FROM myshowcam.chat_category_images AS ChatCategoryImage WHERE ChatCategoryImage.chat_category_id = 5 LIMIT 10
What is the problem and why its not coming ORDER BY Frequency in the second query?
Thanks
chinu
You can use virtualFields
$this->ChatCategoryImage->virtualFields = array('Frequency' => 'hits/(DATEDIFF(NOW(),created))');
changing the way of order
$order = array('Frequency' => 'desc');
This happened to me to. You have to add to the paginate function the third parameter $whitelist. For example.
$this->Paginator->settings = array(
'conditions'=>array('ChatCategoryImage.chat_category_id'=>$cetegory_id),
'fields'=>$fields,
'limit' => 10,
'order' => $order,
);
$scope = array();
$whitelist = array('ChatCategoryImage.id', ...); //The fields you want to allow ordering.
$getCategoryImages = $this->Paginator->paginate('ChatCategoryImage', $scope, $whitelist);
pr($getCategoryImages);
I do not know why this is happening. I tried to see the code inside the paginate function but i could not figure it out.
Your code was lil wrong
$this->paginate = array(
'conditions' => array('ChatCategoryImage.chat_category_id'=>$cetegory_id),
'limit' => 10, 'order' => 'Frequency' => 'DESC');
$getAllCourses = $this->paginate('ChatCategoryImage');

Get results in magento just like BETWEEN keyword in SQL

I've got this problem that I can't solve. Partly because I can't explain it with the right terms. I'm new to this so sorry for this clumsy question.
Below you can see an overview of my goal.
I'm using Magento CE 1.7.0.2
In SQL we have a keyword BETWEEN for filter the records between two values.
For Example: Select * from Mytable where rollnum BETWEEN 10 AND 100;
Like that I want to use in Magento
$_productCollection = Mage::getResourceModel('reports/product_collection')->addAttributeToSelect('*')->setOrder($choice, 'asc');
in the above i want to use that & that should work just like BETWEEN keyword in SQL..
Any Ideas....
$collection->addAttributeToFilter('start_date', array('date' => true, 'to' => $todaysDate))
->addAttributeToFilter('end_date', array(
array('date' => true, 'from' => $todaysDate),
array('null' => true)
)
Simple way, taking your problem :
$_productCollection->addAttributeToFilter(
array(
'attribute' => 'rollnum',
'in' => array(10, 100)
)
);

zend framework 2 and doctrine query builder

I am trying to write a query using the doctrine query builder based on the parameters i am getting from an array.
Here's my array,
$query = array('field' => 'number,
'from' => '1',
'to' => '100',
'Id' => '2',
'Decimation' => '10'
);
The query that i am trying to write is,
select * from table where (number between 1 AND 100) AND (Id = 2) AND number mod 10 = 0
Here's where i stand now,
if (is_array($parameters['query'])) {
$queryBuilder->select()
->where(
$queryBuilder->expr()->between($parameters['query']['field'], $parameters['query']['from'], $parameters['query']['to']),
$queryBuilder->expr()->eq('Id', '=?1'),
$queryBuilder->expr()->eq($parameters['query']['field'],'mod 10 = 0')
)
->setParameter(array(1 => $parameters['query']['Id']));
}
I just cant wrap my head around this for some reason. Help !! anyone?
Not tested or anything, just directly typed into SO answer box:
$queryBuilder->select('table')
->from('My\Table\Entity', 'table')
->where($queryBuilder->expr()->andX(
$queryBuilder->expr()->between('table.number', ':from', ':to'),
$queryBuilder->expr()->eq->('table.id', ':id'),
))
->andWhere('MOD(table.number, :decimation) = 0')
->setParameters(array(
'from' => $parameters['query']['from'],
'to' => $parameters['query']['to'],
'id' => $parameters['query']['id'],
'decimation' => $parameters['query']['decimation']
));
It does not dynamically let you set which field to apply the where condition to. However, this is most likely a bad idea without whitelisting the values you want to allow. Once this is done a simple modification to the code above (just interpolate the value in place of number in the table.number string).
I kinda got it,
The main idea here was to use the andWhere clause. Multiple where clauses was what i wanted. and the mod operator that doctrine gives. Worked out pretty well. In between the requirement changed as well.

Categories