cakephp created query for exact date - php

Trying to figure out how to find all records from database that were created on a specific day but I'm having a hard time coming up with the necessary conditions. This is what I have so far:
$date = new DateTime('2012-11-25');
$users = $this->User->find('all', array('conditions' => array('User.created > ' => $date)));
But this is giving me more than just the specified day. How can I adjust the condition so that it returns all users that were created only on November 25th?

Your code has a greater than symbol in it.
$users = $this->User->find('all', array('conditions' => array('User.created > ' => $date)));
try without:
$users = $this->User->find('all', array('conditions' => array('User.created' => $date)));

you should use the CakeTime method for this or manually assert that you only check on the date part of this particular day.
http://book.cakephp.org/2.0/en/core-utility-libraries/time.html#CakeTime::dayAsSql
'conditions' => CakeTime::dayAsSql($date, 'created')

After playing around, I finally was able to get it to work. Hopefully this can help somebody else out there that runs across the same situation:
$date = new DateTime('2012-11-25');
$users = $this->User->find('all', array('conditions' => CakeTime::dayAsSql($date, $date, 'User.created')));
The key was making sure to provide the $date twice.

Related

Symfony mongo-odm-aggregation-bundle sums

For start, I have to say I am new to mongo (3.2). I am using mongo-odm-aggregation-bundle for php framework Symfony (2.8.4). I want to get sums of some fields restricted by dates.
So far, I managed to get sums for all records:
$expr = new \Solution\MongoAggregation\Pipeline\Operators\Expr;
$aq = $this->manager->getCollection('AppBundle:UserDaySums')->createAggregateQuery()->group([
'_id' => 'client.$id',
'total' => $expr->sum('$aSum'),
])
Now, I'd like to restrict this query by dateFrom,dateTo and userId. I am not sure, how to do it. I know, I should probably use match function, but I don't know how. Or is there some better solution?
Thanks for replies!
KP
Yes, you can use the match function. For example, the following assumes you have the date variables for use in the query:
$expr = new \Solution\MongoAggregation\Pipeline\Operators\Expr;
$aq = $this->manager->getCollection('AppBundle:UserDaySums')->createAggregateQuery();
$dateFrom = new MongoDate(strtotime('-2 days'));
$dateTo = new MongoDate();
$userId = 'Xsgy62js0lb';
$result = $aq->match(['dateFrom'=>$dateFrom, 'dateTo'=>$dateTo, 'userId'=>$userId ])
->group(['_id'=>'client.$id', 'total'=>$expr->sum('$aSum') ])
->getQuery()->aggregate();
In my case, match() was somewhat tricky on a MongoId object.
This didn't work for me:
$userMongoId = "57321c7a2977f8de306ef648";
$aq ->match([ 'user.$id' => $expr->eq($userMongoId) ])
This worked:
$aq ->match([ 'user' => new \MongoId($userMongoId) ])
Tested on Symfony 3 with the SolutionMongoAggregationBundle, MongoDB version 3.2.6.

using sql MONTH or YEAR in cakephp find queries

I'm trying to get all the users that has registered during a particular month using a query like this in a cakephp application:
$registered_users = $this->User->find('all', array(
'conditions' => array(
'MONTH(User.date)' => 10
)
));
The query above is supposed to return me all the users that has registered during the month of october for example, but for some reason, I get the following error:
1054: Unknown column 'User.date' in 'where clause'
Does anybody know why I'm getting this error please?
Thank you
Try this
$condition['MONTH(date) >'] = '10';
$registered_users = $this->User->find('all', array(
'conditions' => $condition,
));
Sorry I dont have enough points to add this as a comment.
Make sure in your database User.date column actually exists. Maybe you wanted to use User.created?

Why doesn't this PHP MongoDB query return any results even though there is one?

I have a collection of users and users have a meta.create_date field which is an ISODate as seen below. I am trying to count how many users were created in the last N days. I have the following in the database:
{
"_id" : ObjectId("51e61fa16803fa40130a0581"),
"meta" : {
"create_date" : ISODate("2013-07-17T04:37:53.355Z")
}
}
My PHP code:
$daysAgo = new MongoDate(date('c', strtotime('-7 days')));
$query = array(
'meta.create_date' => array(
'$gte' => $daysAgo,
)
);
$result = $this->db->users->count($query);
I have also tried specifying a range using '$gte' and '$lte' where $lte => today.
However, result is coming back as 0. So what is going on here?
MongoDate() takes int time(). So, passing in a php date() to the constructor does not work. This is the proper way:
$daysAgo = new MongoDate(strtotime('-7 days'));

CakePHP Merging date fields to the shortest

I have 2 dates (create, update) that i want to merge in a new column, selecting the newest date... how can I do it?
Here is the array creation:
$this->Message= array(
'fields' => array('Message.id','Message.type','Message.createdate','Message.updatedate'),
'conditions' => $cond);
$messages = $this->Message->find('all', $conditionsMessage);
Now I need another field (lets call it NewDate) Message.NewDate that gets the newest date from Message.createdate and Message.updatedate, so i can call it after in a view using $messages[NewDate]
Help plz...
Thx!
UPDATE:
It's not hard to loop over the array with something like
foreach($messages as $k => $m){
if(strtotime($m['Message']['updatedate']) > strtotime($m['Message']['createdate'])){
$messages[$k]['Message']['NewDate'] = $m['Message']['updatedate'];
}else{
$messages[$k]['Message']['NewDate'] = $m['Message']['createdate'];
}
}
ORIGINAL ANSWER:
I would think that your Message.updatedate would always be the newest date, so you could just select that. But assuming that's not the case for some reason, you can create a virtual field in your model:
public $virtualFields = array(
'NewDate' => "IF(Message.updatedate > Message.createdate, Message.updatedate, Message.createdate)"
);
This uses the MySQL IF() function. If you're not using MySQL you'd have to figure out how to do something similar with your database.
http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_if

How to set current date and time in table field using zend

I am having table called users with following fields ,
is_login(tinyint(1)) and last_login(datetime).
Below is the piece of code to update when user is online using Zend,
public function updateLastLoginDetails($id){
$currentDateTime = date('Y-m-d H:i:s');
$data = array('is_online' => 1,'last_login'=>$currentDateTime);
$this->_db->update( 'users', $data,'id = '.$id);
}
Here i am using $currentDateTime = date('Y-m-d H:i:s'); to store current data and time. But it seems not ok with time.
Kindly suggest me the best way to store current data and time using Zend .
Thanks in Advance,
Dinesh Kumar Manoharan
I'm not exactly sure what's causing your problem, but I find using NOW() to be easier. Also, you should ensure the variable $id gets quoted in the update's where condition.
public function updateLastLoginDetails($id){
$data = array('is_online' => 1, 'last_login' => new Zend_Db_Expr('NOW()'));
$this->_db->update('users', $data, array('id = ?' => $id));
}
It looks like you forgot to use $data anywhere in your code!
public function updateLastLoginDetails($id){
$currentDateTime = date('Y-m-d H:i:s');
$data = array('is_online' => 1, 'last_login'=>$currentDateTime);
$this->_db->update('users', $data, 'id = '. (int)$id);
}
You might want to consider using a TIMESTAMP field in place of a DATETIME for last_login and have MySQL update it automagically.
Hi am I understanding correctly that the year month and day are being inserted correctly but not the hour minutes and seconds? If that is the case can you please provide use with a describe of the users table. Just execute "DESCRIBE users" in phpMyAdmin.
If that is the case it could be that the field is of type DATE and not DATETIME.

Categories