I need max submitted orders in the last 30 days. max field is a virtualField.
public $virtualFields = array(
'max_submitted' => "MAX(`WorkRecord`.`submitted`)"
);
I get error #1054 - Unknown column 'WorkRecord.max_submitted' in 'field list'
SELECT `WorkRecord`.`id`, `Order`.`fee`, `Order`.`order_id`,
`Order`.`min_sources`, `Order`.`min_references`, `Order`.`am_level`,
`Order`.`am_standard`, `Order`.`am_type`, `Order`.`am_subject`, `Order`.`am_word_count`,
`Order`.`ref_style`, `Order`.`service`, `BriefInstalment`.`deadline`,
`BriefInstalment`.`id`, (MAX(`WorkRecord`.`submitted`)) AS `WorkRecord__max_submitted`
FROM `writers`.`work_records` AS `WorkRecord`
RIGHT JOIN `torg`.`temp_orders` AS `Order` ON (`Order`.`order_id` = `WorkRecord`.`order_id` AND `Order`.`status2` > 2 AND `Order`.`am_type` NOT LIKE '%phd%') LEFT JOIN `writers`.`brief_instalments` AS `BriefInstalment` ON (`WorkRecord`.`brief_instalment_id` = `BriefInstalment`.`id`)
WHERE `WorkRecord`.`writer_id` = 7827
AND `WorkRecord`.`withdrawn` IS NULL
AND `WorkRecord`.`max_submitted` BETWEEN NOW() - INTERVAL 30 DAY AND NOW() GROUP BY `Order`.`order_id`
You can't use aggregate function results in where clauses, because the results of the aggregate (e.g. max()) will NOT be available when the where clause is being applied.
Move the max() to a `having:
SELECT ..., max(foo) AS foo
FROM ...
WHERE ...
HAVING foo BETWEEN ...
having is basically applied as the last step just before the results are sent over the client. By that time, all of the calculations/aggregations are done.
For others. Here is what I should have done.
$workRecords = $this->find('all', array(
'fields' => array(
'WorkRecord.id', 'MAX(`WorkRecord`.`submitted`) AS submitted',
'Order.fee', 'Order.order_id', 'Order.min_sources', 'Order.min_references', 'Order.am_level', 'Order.am_standard',
'Order.am_type', 'Order.am_subject', 'Order.am_word_count', 'Order.ref_style', 'Order.service'
),
'conditions' => array(
'WorkRecord.writer_id' => $userId,
'WorkRecord.withdrawn IS NULL'
),
'joins' => array(
array(
'table' => 'torg.temp_orders',
'alias' => 'Order',
'type' => 'RIGHT',
'conditions' => array(
'Order.order_id = WorkRecord.order_id',
'Order.status2 >' => 2,
"Order.am_type NOT LIKE '%phd%'"
)
)
),
'contain' => array(
'BriefInstalment.deadline'
),
'group' => array(
'Order.order_id HAVING `submitted` BETWEEN NOW() - INTERVAL 30 DAY AND NOW()'
)
));
Related
$termscat = get_terms([
'taxonomy' => 'newscategories',
'orderby' => 'count',
'order' => 'DESC',
'hide_empty' => false
]);
I am using above code to get post counts and is returning all post but i want to filter data only by todays date.
I think you want something like this.
SELECT count(post.ID) as count,rel.term_taxonomy_id,terms.name FROM {$wpdb->base_prefix}posts as post INNER JOIN {$wpdb->base_prefix}term_relationships as rel ON post.ID=rel.object_id INNER JOIN {$wpdb->base_prefix}terms as terms ON rel.term_taxonomy_id= terms.term_id WHERE post_date LIKE '$currentDate%' AND post.post_type='$post_type' GROUP BY rel.term_taxonomy_id ORDER BY count DESC
get_terms() used to get terms not posts.
if you want to get posts of current date then you can use the code below
$today = date( 'Y-m-d' );
$args = array(
'post_type' => 'vehicle',
'date_query' => array(
//set date ranges with strings!
'after' => 'today',
//allow exact matches to be returned
'inclusive' => true,
),
);
$query = new WP_Query( $args );
You can get more information on this https://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters
$today['year'] = current_time('Y');
$today['mon'] = current_time('m');
$today['mday'] = current_time('d');
$args = array(
'post_type' => 'news',
'date_query' => array(
array(
'year' => $today['year'],
'month' => $today['mon'],
'day' => $today['mday'],
),
),
'tax_query' => array(
array(
'taxonomy' => $tex_name,
'field' => 'term_id',
'terms' => $term_id,
),
),
);
$query = new WP_Query( $args );
$total = $query->found_posts;
In my CakePHP 2.7.7 app, I have an issue where using PaginatorComponent isn't properly sorting my results. See this link for an image:
Sample Data
The data should be sorted by descending last name, but you can see there are a couple users who are seemingly exempt from this data. Doesn't matter what order I do it in, ascending or descending, these few records don't get sorted. For reference:
index() in UsersController:
public function index() {
$this->User->contain('Status');
$this->paginate = array(
'limit' => 15,
'order' => array('User.last_name' => 'DESC'),
'conditions' => array('User.department_id =' => $this->Session->read('Auth.User.department_id')),
'contain' => 'Status'
);
$this->set('users', $this->Paginator->paginate());
}
Any ideas what could have caused this? I'm at a loss here. Thanks in advance!
SELECT `User`.`id`, `User`.`first_name`, `User`.`last_name`, `User`.`middle`, `User`.`address`, `User`.`address_2`, `User`.`city`, `User`.`state_id`, `User`.`zip`, `User`.`home`, `User`.`cell`, `User`.`work`, `User`.`email`, `User`.`status_id`, `User`.`status_reason`, `User`.`rank`, `User`.`birthday`, `User`.`gender`, `User`.`school`, `User`.`employer`, `User`.`position`, `User`.`created`, `User`.`modified`, `User`.`updated_by`, `User`.`radio`, `User`.`ident`, `User`.`parent_name`, `User`.`parent_number`, `User`.`parent_email`, `User`.`squad`, `User`.`squad_leader`, `User`.`ride_along`, `User`.`drivers_license`, `User`.`username`, `User`.`password`, `User`.`department_id`, `User`.`join_date`, `User`.`group_id`, `User`.`test`, (CONCAT(`User`.`first_name`, " ", `User`.`last_name`)) AS `User__name`, `Status`.`id`, `Status`.`status` FROM `admin_cake`.`users` AS `User` LEFT JOIN `admin_cake`.`statuses` AS `Status` ON (`User`.`status_id` = `Status`.`id`) WHERE `User`.`department_id` = 1 ORDER BY `User`.`last_name` ASC LIMIT 15
When you use $this->paginate to set conditions, limit...you need to use function $this->pagination().
$this->pagination and $this->Paginator->pagination() can not be combined.
1)
public function index() {
$this->User->contain('Status');
$this->paginate = array(
'limit' => 15,
'order' => array('User.last_name' => 'DESC'),
'conditions' => array('User.department_id =' => $this->Session->read('Auth.User.department_id')),
'contain' => 'Status'
);
// Assign settings
$this->Paginator->settings = $this->paginate;
$this->set('users', $this->Paginator->paginate());
}
2)
public function index() {
$this->User->contain('Status');
$this->paginate = array(
'limit' => 15,
'order' => array('User.last_name' => 'DESC'),
'conditions' => array('User.department_id =' => $this->Session->read('Auth.User.department_id')),
'contain' => 'Status'
);
//Don't use $this->Paginator->paginate()
$this->set('users', $this->paginate());
}
I have a table 'activities' and the columns are grouped by three of its attributes. Now I want to fetch Activity ID that is randomly selected from all the set of groups. The query is as follows:
$act = $this->find('all', array('conditions' => $cond,
'limit' => $limit,
'fields' => array('count(*) as count, Activity.id as id'),
'page' => $page,
'group' => $group,
));
These are the things I tried and none of them worked.
1. Create a self join which should have random records
$this->bindModel(array(
'belongsTo' => array(
'Random' => array(
'className' => 'Activity',
'order' => 'rand()',
'foreignKey' => 'id',
'fields' => 'Random.id'
)
)
));
This failed because the rand() order is appended in the end which simply randomizes all fetched activities.
Added a join option
'joins' => array(
array(
'table' => 'activities',
'alias' => 'Random',
'type' => 'LEFT',
'conditions' => array(
'Activity.id = Random.id'
),
'fields' => 'Random.id',
'order' => 'rand()'
)
This also didn't work as order value is not parsed by Cake
Tried to add condition
'Activity.id >= floor(rand() * (max(Activity.id) - min(Activity.id)) - min(Activity.id))'
Gave a mysql error
Please help me out
Assuming that your query is working:
$act = $this->find('all', array('conditions' => $cond,
'limit' => $limit,
'fields' => array('count(*) as count, Activity.id as id'),
'page' => $page,
'group' => $group,
'order' => 'rand()',
'limit' => '1' // if you only want one random activity ID
));
Ok finally figured it out. We need to hack the way cake php works. In place of table name, I wrote a query to fetch randomly ordered records. Also notice the join type is 'right'. Left join wont produce randomly sorted list
$activities = $this->find('all', array('conditions' => $cond,
'page' => $page,
'limit' => $limit,
'fields' => array('count(*) as count, Random.id as id, max(Activity.modified) as Modified'),
'group' => $group,
'order' => 'Modified desc',
'joins' => array(
array(
'table' => '(select * from activities order by rand())',
'alias' => 'Random',
'type' => 'RIGHT',
'conditions' => array(
'Activity.id = Random.id'
),
)
)
));
I am using LEFT join and as a result getting null values for is_read column in Messages table. I want to keep the nulls at bottom when ordering. I'm using this in paginator. Following is the my code for doing the same:
$this->Paginator->settings = array(
'fields' => array('User.*'),
'joins' => array(
array('table' => 'messages',
'alias' => 'Message',
'type' => 'LEFT',
'conditions' => array(
'User.id = Message.user_from_id'
)
),
),
'limit' => 20,
'group' => array('User.id'),
'order' => array('ISNULL(Message.is_read)' => 'asc','Message.is_read' => 'asc', 'Message.created' => 'asc'),
);
The query Cakephp generates for this is as follows:
SELECT `User`.*, (CONCAT(`User`.`first_name`, ' ', `User`.`last_name`)) AS `User__full_name` FROM `srs_development`.`users` AS `User` LEFT JOIN `srs_development`.`messages` AS `Message` ON (`User`.`id` = `Message`.`user_from_id`) WHERE 1 = 1 GROUP BY `User`.`id` ORDER BY `Message`.`is_read` asc, `Message`.`created` asc LIMIT 20
ISNULL function is getting omitted in the final query.
Also please suggest a way to accomplish this without using custom pagination() if possible.
Aggregate functions didn't work in the order clause when using Pagination component. I tried declaring a virtual field in Message model as:
public $virtualFields = array(
'sortme' => "ISNULL(Message.is_read)",
);
So finally, declaring it as virtual field in the Message model did the job.
Thank you everyone.
my problem is very simple. I have a table named 'articles' and I'd like to get the first three recent articles order DESC. But I want also these articles be displayed if their publication date is older or equal to today. So I've had an other condition in my request. My cakephp code is the following :
$this->set('lastArticles', $this->Article->find('all', array(
'conditions' => array('Article.visible' => true),
'Article.publication_date <= ' => date('Y-m-d'),
'order' => array('Article.creation_date DESC', 'Article.id DESC'),
'limit' => 3
)));
But the problem is even if the articles with a publication date > date('Y-m-d') these ones are displayed too! Does anyone have an idea ? Thanks in advance for your answer.
Looks like your publication_date condition isn't in the conditions array. Your code should look like this:
$this->set('lastArticles', $this->Article->find('all',
array(
'conditions' => array(
'Article.visible' => true,
'Article.publication_date <= ' => date('Y-m-d')
),
'order' => array(
'Article.creation_date DESC',
'Article.id DESC'
),
'limit' => 3
)));
A bit of extra indentation and whitespace is your friend here.
See this
$conditions = array(
'Article.visible' => true,
'Article.publication_date <= ' => date('Y-m-d')
);
$order = array('Article.creation_date DESC', 'Article.id DESC');
$lastArticles = $this->Article->find('all', array(
'conditions' => $conditions,
'order' => $order,
'limit' => 3
);
$this->set('lastArticles', $lastArticles);