Objective: Trying to get all posts on a certain date from the db table(say, I've datetime in the format '2019-03-07 12:30:00' then I would like to get all posts from this date '2019-03-07').
As I need posts from this date, I'm converting the given datetime to i18nFormat date format. As below ::
$userSelectedDate = $selectedDate->i18nFormat('yyyy-MM-dd');
then, On the where clause, I'm using mySql DATE function on table field and it returns me expected result. code as below:
$conn = connectionManager::get('default');
$conn->begin();
$stmt = $conn->prepare(
"SELECT * FROM `blogs`
where DATE(`PUBLISHED_DATE`) = '$userSelectedDate'"
);
$stmt->execute();
$conn->commit();
This works fine. But I would like to convert it to Cakephp 3 way as below.
$query = $this
->find()
->where([
DATE($this->aliasField('PUBLISHED_DATE')) => $userSelectedDate
])
;
This obviously throws an error as below.
Error: [PDOException] SQLSTATE[42S22]: Column not found: 1054 Unknown column
How to use mysql DATE function in Cakephp 3 query? I've checked other related answers and I couldn't find a way.
Managed to find the answer.
$query = $this->find("all", [
'conditions' => [
'DATE(PUBLISHED_DATE)' => $selectedDate->i18nFormat('yyyy-MM-dd')
]
]
);
Related
Cakephp informs me that it cannot find the table or does not recognize the alias what am i supposed to use?
Hello i am new to cake php ORM can any one tell me how to preform a left join on a subquery I'm really interested to know how to use in working the join
Here is sub query and left join so far please ignore any syntax error
$scl = TableRegistry::get('School');
$subquery = $scl->find();
$subquery->select([
'UID',
'SID',
'Total' => $subquery->func()->sum('numberOfStudents')
])->group(['UID, SID']);
$q->select([
'TeacherID',
'ClassID',
'StudentTotal' => 'sq.Total'
])->join([
'table' => $subquery,
'alias' => 'sq',
'type' => 'LEFT',
'conditions' => ['sq.UID = TeacherID', 'sq.SID = ClassID']
]);
here is the error:
[PDOException] SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sq.UID' in 'on clause'
The problem is that ORM based queries automatically alias the selected fields, so you don't get
SELECT UID, SID ...
but
SELECT UID as School__UID, SID as School__SID
hence referring to sq.UID will fail, as no such field name was selected.
To avoid this problem you can either use an alias that matches the original field name:
->select([
'UID' => 'UID',
'SID' => 'SID',
// ...
])
use the lower level database query that doesn't automatically create aliases:
$subquery = $scl
->getConnection() // connection() in older CakePHP versions
->newQuery()
->from($scl->getTable()); // table() in older CakePHP versions
or refer to the aliased fields in the main query:
'conditions' => [
'sq.' . $scl->getAlias() . '__UID = TeacherID', // alias() in older CakePHP versions
'sq.' . $scl->getAlias() . '__SID = ClassID',
]
I am trying to pull record from a table using the following code
$userId = Yii::$app->user->id;
$lists = PromoLists::findAll(['user_id' => $userId, 'list_type' => 'custom']);
which outputs a query like below
select * from promo_lists where user_id ='$userId' and list_type='custom'
But i am unable to find any thing in the documentation that would help me achieve it with the following condition.
select * from promo_lists where user_id ='$userId' and list_type='custom' and status!='deleted'
as the status is an ENUM field and there are 4 different status
'active','pending','rejected','deleted'
currently i used the following approach
PromoLists::findAll(['user_id' => $userId, 'list_type' => 'custom', 'status'=>['active','pending','rejected']]);
which outputsthe following query
select * from promo_lists where user_id ='$userId' and list_type='custom' and status in ('active','pending','rejected')
which somehow achieves the same thing but this query would need to be edited every time when there is a new status type added to the table column status.
i know i can do this by using PromoLists::find()->where()->andWhere()->all()
but how to check with != / <> operator using findAll().
Simply like this:
PromoLists::find()->where(['and',
[
'user_id' => $userId,
'list_type' => 'custom',
],
['<>', 'status', 'deleted'],
])->all();
Using operator format in condition
http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html#operator-format
PromoLists::find()
->andWhere([
'user_id' => $userId,
'list_type' => 'custom',
['!=', 'status', 'deleted']
])
->all();
I want to get those records whose date_last_copied field is empty or less than the current date. I tried this, but it did not give me the desired result:
$tasks = $this->Control->query("
SELECT *
FROM
`controls`
WHERE
`owner_id` = ".$user_id."
AND `control_frequency_id` = ".CONTROL_FREQUENCY_DAILY."
OR `date_last_copied` = ''
OR `date_last_copied` < ". strtotime(Date('Y-m-d'))."
");
Current query looks something like this, I think. That is, find the records with the correct owner_id and frequency_id, where the date_last_copied is null or less than a certain date. Is that logic correct?
SELECT *
FROM controls
WHERE owner_id = ::owner_id::
AND control_frequency_id = ::frequency_id::
AND (
date_last_copied IS NULL
OR date_last_copied < ::date::
)
But we should really be using the CakePHP query builder, rather than running raw SQL. This article gives some details. If I were to take a stab at a solution, we'd want something like the following. But we ideally want someone from the CakePHP community to chime in here. EDIT: Note that this seems to be for CakePHP 3.0, only.
// Build the query
$query = TableRegistry::get('controls')
->find()
->where([
'owner_id' => $ownerId,
'control_frequency_id' => $frequencyId,
'OR' => [
['date_last_copied IS' => null],
['date_last_copied <' => $date]
]
]);
// To make sure the query is what we wanted
debug($query);
// To get all the results of the query
foreach ($query as $control) {
. . .
}
I'm suggesting this, rather than the raw SQL string you have above, because:
We can now leverage the ORM model of CakePHP.
We don't have to worry about SQL injection, which you're currently vulnerable to.
EDIT: OK, this is a guess at the syntax applicable for CakePHP 2.0... YMMV
$controls = $this->controls->find('all', [
'conditions' => [
'owner_id' => $ownerId,
'control_frequency_id' => $frequencyId,
'OR' => [
['date_last_copied IS' => null],
['date_last_copied <' => $date]
]
]
];
Otherwise, we just use the raw query as a prepared statement:
$result = $this->getDataSource()->fetchAll("
SELECT *
FROM controls
WHERE owner_id = ?
AND control_frequency_id = ?
AND (
date_last_copied IS NULL
OR date_last_copied < ?
)",
[$ownerId, $frequencyId, $date]
);
Not sure about your whole logic but your final query statement should be something like:
SELECT * FROM `controls` WHERE (`owner_id` = <some owner_id>)
AND (`control_frequency_id` = <some id value>)
AND (`date_last_copied` = '' OR
`date_last_copied` IS NULL OR
`date_last_copied` < CURDATE() )
Use parentheses carefully to match your logic.
Always specify the version of cakePHP you are using for your App.
This query should work fine in CakePHP 3.0 for SQL AND and OR.
$query = ModelName>find()
->where(['colunm' => 'condition'])
->orWhere(['colunm' => 'otherCondition'])
->andWhere([
'colunm' => 'anotherContion',
'view_count >' => 10
])
->orWhere(['colunm' => 'moreConditions']);
Hi everyone i have one question search result month in using MySql or Cakephp my table name is state_supplies and data are
MySql query is:
SELECT * FROM `state_supplies` WHERE created=DATE_FORMAT(NOW(), '%m')
Cakephp search code is
$this->StateSupply->find('all', array(
'conditions'=> array(
'unitid'=>$this->Session->read('Auth.User.unitid'),
'created'=>'MONTH(CURDATE())'
)
)
);
Try this:
In Mysql:
$first_day_this_month = date('Y-m-01 H:i:s'); // hard-coded '01' for first day
$last_day_this_month = date('Y-m-t H:i:s');
$sql="SELECT * FROM state_supplies WHERE created between '$first_day_this_month' and '$last_day_this_month' "
Cakephp code
Details
Update code for right answer
$this->StateSupply->find('all',array(
'conditions'=>array(
'unitid'=>$this->Session->read('Auth.User.unitid'),
'crop'=>$this->request->data['StateSupply']['crop'],
'state'=>$this->request->data['StateSupply']['state'],
'created BETWEEN ? AND ?'=>array(date('Y-m-01',strtotime('this month')),date('Y-m-t',strtotime('this month')))
)
)
);
I am trying to extract the latest id of the table called gal_providers
//get the id of the last gal_provider add.
$order = array("GalProvider.id DESC");
$gal_provider_id = $this->GalProvider->field("id",array("order"=>$order));
$this->data["User"]["username"] = "gal_provider_".$gal_provider_id;
But it shows error like :
Warning (512): SQL Error: 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 'order = ('GalProvider.id DESC') LIMIT 1'
at line 1 [CORE/cake/libs/model/datasources/dbo_source.php, line 684]
Query: SELECT GalProvider.id FROM gal_providers AS GalProvider
WHERE order = ('GalProvider.id DESC') LIMIT 1
Whats wrong with the code ?
try to change this:
$order = array("GalProvider.id DESC");
to this:
$order = array('GalProvider.id' => 'desc');
or try this:
$gal_provider_id = $this->GalProvider->field("id",array('order' => array('GalProvider.id' => 'desc')));
As noted in the CakePHP documentation, the second argument of the Model::field() method is for a condition, and the third is for the order.
Also looking at the documentation, we can see that by default the condition and order arguments are null - which means we can do the same.
Try this:
$gal_provider_id = $this->GalProvider->field("id", null, "id DESC");
$this->data["User"]["username"] = "gal_provider_".$gal_provider_id;
In your example, you're using the Model::field() method as if it were the Model::find() method (they are two different methods and require different formats for their arguments)
Alternatively, we can use the find method itself:
$gal_provider = $this->GalProvider->find('first', array(
'fields' => array('GalProvider.id'),
'order' => 'GalProvider.id DESC',
'recursive' => -1 // more efficient (ensures no joins made for the query)
));
$this->data["User"]["username"] = "gal_provider_".$gal_provider['GalProvider']['id'];