CakePHP query: where condition with calculated fields - cakephp

I have the followwing problem with creating a query in CakePHP 3:
For the Entity Recordings I want to calculate the age as the difference between the year of the two dates "collection date" and "birthdate"
$query = $this->Recordings->find()
->select(['age' => 'Year(Recordings.collection_date) - Year(Athletes.birthdate)'])
->select($this->Recordings)
->select($this->Recordings->Athletes);
When I try to filter with the following where clause
$query = $query->where(['Year(Recordings.collection_date) - Year(Athletes.birthdate) =' => $age]);
The SQL Code which is created has the Athletes beeing modified to lowercase.
WHERE
( Year(Recordings.collection_date) - year(athletes.birthdate) = '17' )
How do I have to write the where clause correctly? I havent found a way to use Identifiers or query functions like
$year = $q->func()->year(['Athletes.birthdate' => 'identifier']);
to bild the conditions.
Any hints are welcome.

Related

CakePHP 3.x case statement on order

I am trying to use a CASE statement on the order of a MySQL statement in CakePHP 3.x app. The simple select is as follows:
$articles = $this->Articles->find()
->where($conditions)
->order(function ($exp, $q) {
return $exp->addCase(
[
$q->newExpr()->gt('Articles.modified', (new Time())->subDays(365)) // article has been updated in the last x days
],
['priority'], # values matching conditions
['string'] # type of each value
);
})
->limit(15)
->all();
The following SQL is generated:
SELECT `Articles`.`id` AS `Articles__id`, ....
FROM `articles` `Articles`
WHERE (`publish` < :c0 AND `Articles`.`publish` > :c1)
ORDER BY CASE WHEN `Articles`.`modified` > :c2 THEN :param3 END LIMIT 15
The case statement is not correct because it is missing the DESC order which should come after the 'END' - see this fiddle:
http://sqlfiddle.com/#!9/8df161/5
I'm not sure if this is a limitation with how CakePHP handles CASE?
Further I require a second order after the case statement to order by 'publish' desc.
Expressions passed to Query::order() must generate everything required by the ORDER BY clause, including the direction keyword.
If the expression that you're using doesn't support that, then you can use Query::oderAsc() or Query::oderDesc(), which will append the respective direction keyword accordingly.
$query = $this->Articles->find();
$query
->where($conditions)
->orderDesc(
$query->newExpr()->addCase(/* ... */)
)
// ...
See also
Cookbook > Database Access & ORM > Query Builder > Selecting Data

Cakephp How to use SQL month function in cakephp find method

I have a query like
SELECT count(id),DATE_FORMAT(created,'%M') from searches group by month(created)
The output that I got like
count(id) DATE_FORMAT(created,'%M')
16 August
2 September
I applied this query in cakephp find method like below
$total = $this->Searches->find('count',[
'fields'=>['Searches.id',DATE_FORMAT('created','%M')],
'group' =>[month('Searches.created')]
]);
1st I am getting error date_format() expects parameter 1. How can I apply my top sql query in cakephp find method ?
I am using cakephp 3 version.
The query builder has a func() method that allows you to use SQL functions.
http://book.cakephp.org/3.0/en/orm/query-builder.html#using-sql-functions
$time = $query->func()->date_format([
'created' => 'identifier',
"'%M'" => 'literal'
]);
You can then use that $time variable in your query.

Pagination of query ignoring the LIMIT clause in CakePHP 3.x

I am trying to create a query that would only return 2 results, and by following the documentation I get the query to run, however the limit is still set to 20 by default.
Here is how the query is built:
$upcomingMeetings = $this->Meetings->find('all')
->where(['Meetings.user_id' => $this->Auth->User('user_id')])
->andWhere(["Meetings.date >= " => date('Y-m-d') ])
->order(['Meetings.date' => 'ASC'])
->limit(2);
The result is being passed to the view like following:
$this->set('upcomingMeetings', $this->paginate($upcomingMeetings));
Here is the query that is being run on the database:
SELECT
Meetings.id AS `Meetings__id`,
Meetings.date AS `Meetings__date`,
Meetings.user_id AS `Meetings__user_id`,
FROM
meetings Meetings
WHERE
(
Meetings.group_id = 7
AND Meetings.date >= '2016-01-14'
)
ORDER BY
Meetings.date ASC
LIMIT
20 OFFSET 0
Any help or guidance is much appreciated.
When paginating a Query object, CakePHP will ignore the limit() clause and use the value defined in the $paginate configuration array instead.
This is what can be concluded after inspecting the source code.
Try adding the following to your controller:
public $paginate = [
'limit' => 2,
];

CakePHP 3 format date in select query

I am using CakePHP 3 in my project and I came across of a need to format date for date_joined and date_inactivefield in my report. I can use native select query with date function to format date for the field, but in CakePHP, I am not sure how can I integrate date format in select query.
$query = $this->CustomersView->find();
$query->select(['id','contact_person',''date_joined',
'date_inactive','comments','status']);
$query->toArray();
UPDATE
I also tried one of the example from CakePHP online resource
$date = $query->func()->date_format([
'date_joined' => 'literal',
'%m-%d-%y' => 'literal'
]);
$query->select(['id','contact_person',''date_joined',
'date_inactive','comments','status']);
$query->toArray();
But it throws me error below:
'Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%m-%d-%y)) AS `datejoined`, CustomersView.date_inactive AS `CustomersView__date_' at line 1'
SQL query generated by CakePHP:
SELECT CustomersView.id AS `CustomersView__id`,
CustomersView.contact_person AS `CustomersView__contact_person`,
(date_format(date_joined, %m-%d-%y)) AS `datejoined`,
CustomersView.date_inactive AS `CustomersView__date_inactive`,
CustomersView.comments AS `CustomersView__comments`,
CustomersView.status AS `CustomersView__status`
FROM customers_view CustomersView
Any help is really appreciated. :)
Thanks,
Ray
If the date fields are of an appropriate type in your schema (e.g. DATETIME), Cake will return DateTime objects that can be formatted using plain PHP - you don't need to do it in the select.
Example:
$query = $this->CustomersView->find();
$query->select(['id','contact_person','date_joined',
'date_inactive','comments','status']);
$array = $query->toArray();
foreach ($array as $row) {
echo $row["date_joined"]->format("dMY");
}
Let's say for example that your query only returned one row, and the date_joined field here was set to 2015-12-21 23:55:00. The above code would simply print out 21Dec2015.
You can use the DATE_FORMAT($field, %d-%m-%Y) from MySQL.
Here it is an example:
$query = $this->CustomersView->find();
$query->select(['id','contact_person',''DATE_FORMAT(date_joined, "%d-%m-%Y")',
'date_inactive','comments','status']);
Fixed the problem with below code:
$query = $this->CustomersView->find();
$date = $query->func()->date_format([
'date_joined' => 'literal',
"'%m-%d-%y'" => 'literal'
]);
$query->select(['id', 'contact_person', 'date_joined' => $date,
'date_inactive', 'comments', 'status']);
$query->toArray();

I need to count the today created account in Cake 3

I need to count the users, but my condition is only if their account have been created today. I have a users table with a created field (datetime) for each rows. How can i do it in Cakephp, i didn't find the answer in the documentation.
$usersNewCount = Number::format($this->Users->find()->where(['created' => 'CURDATE()'])->count());
I tried with CURDATE, and of course it's not working, i guess Cakephp has a specific function for te datetime field ?
What you are doing there won't work for various reasons.
You cannot pass SQL snippets in the value part of the conditions array, it will be escaped and you'll end up with a string comparison like created = 'CURDATE()', you'd either have to pass the whole condition as a string, or use raw expressions.
Even when properly passing CURDATE(), the comparison won't work as the created column has a time part.
While it is possible to circumvent the former problem by transforming the column, you should try to avoid that whenever possible! Comparing to calculated columns like DATE(created) = CURDATE() will make using indices impossible, and thus massively degrade performance!
So unless you have an extra column that holds just the date part, your best bet is a BETWEEN comparison which is the equivalent to a >= x AND a <= y, and in order to stay cross DBMS compatible, this is best to be done by passing dates from PHP, ie not using DBMS specific date and time functions like CURDATE().
$this->Users
->find()
->where(function (\Cake\Database\Expression\QueryExpression $exp, \Cake\ORM\Query $query) {
$from = (new \DateTime())->setTime(0, 0, 0);
$to = (new \DateTime())->setTime(23, 59, 59);
return $exp->between('Users.created', $from, $to, 'datetime');
})
->count()
This will create a query similar to
SELECT
(COUNT(*)) AS `count`
FROM
users Users
WHERE
Users.created BETWEEN '2015-05-26 00:00:00' AND '2015-05-26 23:59:59'
See also
API > \Cake\Database\Expression\QueryExpression::between()
You can do it this way
$usersNewCount = Number::format($this->Users->find()->where([
'DATE(created) = CURDATE()'
])->count());
Note that passing it in form where(['DATE(created)' => 'CURDATE()']) will not work, since CURDATE() will be interpreted as a string.
When doing 'created' => 'CURDATE()' you are checking for a complete match, getting '2015-05-26', without a time. You need to check for a time interval:
$usersNewCount = Number::format(
$this->Users->find()->where([
'created >=' => date('Y-m-d').' 00:00:00',
'created <=' => date('Y-m-d').' 23:59:59'
])->count());

Resources