I want to make a MySQL query in CakePHP 2.0 which looks like this:
select p.ciname HOSTNAME
,a.status HPSA
,m.status SM9
,p.status LDAP
from hpsas a, hpsms m, ldaps p
where (p.ciname = a.ciname)
and (p.ciname = m.ciname)
order by p.ciname;
Is this possible?
You can make arbitrary SQL queries in CakePHP using the Model.query() method. For example, in a controller:
$sql = ...your sql here...
$results = $this->ModelName->query($sql);
if you are trying to make this query using cake ORM I think this would be a step in that direction:
$options = array();
$options['fields'] => array('p.ciname AS HOSTNAME', 'a.status AS HPSA', 'm.status AS SM9', 'p.status AS LDAP');
$options['joins'][] => array('table' => 'hpsas', 'alias' => 'a', 'conditions' => array('p.ciname = a.ciname'));
$options['joins'][] => array('table' => 'hpsms', 'alias' => 'm', 'conditions' => array('p.ciname = m.ciname'));
$result = $this->Test->find('all', $options);
Those fields and table names don't comply with cake convention, understandable if you are migrating or integrating your project. If you are starting now, you might want to rename them.
http://book.cakephp.org/1.3/en/view/901/CakePHP-Conventions
Related
I am using Query Builder with multiple where clause. When I use this query,
$query1 = new \yii\db\Query();
$query1->select('*')
->from('assessment_score ca')
->where(['AND','ca.is_status' => 0, 'ca.assessment_type' => 'CONTINUOUS ASSESSMENT', 'ca.ca_type' => 'CONTINUOUS ASSESSMENT'])
->andFilterWhere(['ca.state_office_id' => $model->report_state_office_id])
->andFilterWhere(['ca.study_centre_id' => $model->report_study_centre_id])
->andFilterWhere(['ca.programme_id' => $model->report_programme_id])
->andFilterWhere(['ca.department_id' => $model->report_department_id])
->andFilterWhere(['ca.academic_level_id' => $model->report_academic_level_id])
->andFilterWhere(['ca.academic_year_id' => $model->report_academic_year_id])
->andFilterWhere(['ca.academic_semester_id' => $model->report_academic_semester_id])
->andFilterWhere(['ca.course_id' => $model->report_course_id]);
$command=$query1->createCommand();
$ca_data=$command->queryAll();
I got this error
Then, when I changed the code to this, no response:
$selected_list = $_POST['ca'];
$query1 = new \yii\db\Query();
$query1->select('*')
->from('assessment_score ca')
->where(['ca.is_status' => 0])
->andWhere(['ca.assessment_type' => 'CONTINUOUS ASSESSMENT'])
->andWhere(['ca.ca_type' => 'CONTINUOUS ASSESSMENT'])
->andFilterWhere(['ca.state_office_id' => $model->report_state_office_id])
->andFilterWhere(['ca.study_centre_id' => $model->report_study_centre_id])
->andFilterWhere(['ca.programme_id' => $model->report_programme_id])
->andFilterWhere(['ca.department_id' => $model->report_department_id])
->andFilterWhere(['ca.academic_level_id' => $model->report_academic_level_id])
->andFilterWhere(['ca.academic_year_id' => $model->report_academic_year_id])
->andFilterWhere(['ca.academic_semester_id' => $model->report_academic_semester_id])
->andFilterWhere(['ca.course_id' => $model->report_course_id]);
$command=$query1->createCommand();
$ca_data=$command->queryAll();
How do I re-write the code appropriately to solve the issue of multiple where clause?
You might need to change the query format for the where() statement as you need to provide every condition (name=>value pair) as a separate array rather than just name=>value pairs, you currently have
->where(['AND', 'ca.is_status' => 0, 'ca.assessment_type' => 'CONTINUOUS ASSESSMENT', 'ca.ca_type' => 'CONTINUOUS ASSESSMENT'])
which will create the query like below if no other parameter is provided for andFilterWhere() statements.
SELECT * FROM `assessment_score` `ca`
WHERE (0)
AND (CONTINUOUS ASSESSMENT) AND (CONTINUOUS ASSESSMENT)
which is incorrect and throwing the error, you can notice that in your Exception image, so change it to the one below
->where(['AND',
['ca.is_status' => 0],
['ca.assessment_type' => 'CONTINUOUS ASSESSMENT'],
['ca.ca_type' => 'CONTINUOUS ASSESSMENT']
])
which will output the query like
SELECT * FROM `assessment_score` `ca`
WHERE (`ca`.`is_status`=0)
AND (`ca`.`assessment_type`='CONTINUOUS ASSESSMENT')
AND (`ca`.`ca_type`='CONTINUOUS ASSESSMENT')
Your complete query should look like this
$query1 = new \yii\db\Query();
$query1->select('*')
->from('assessment_score ca')
->where(['AND',
['ca.is_status' => 0],
['ca.assessment_type' => 'CONTINUOUS ASSESSMENT'],
['ca.ca_type' => 'CONTINUOUS ASSESSMENT']
])
->andFilterWhere(['ca.state_office_id' => $model->report_state_office_id])
->andFilterWhere(['ca.study_centre_id' => $model->report_study_centre_id])
->andFilterWhere(['ca.programme_id' => $model->report_programme_id])
->andFilterWhere(['ca.department_id' => $model->report_department_id])
->andFilterWhere(['ca.academic_level_id' => $model->report_academic_level_id])
->andFilterWhere(['ca.academic_year_id' => $model->report_academic_year_id])
->andFilterWhere(['ca.academic_semester_id' => $model->report_academic_semester_id])
->andFilterWhere(['ca.course_id' => $model->report_course_id]);
$command = $query1->createCommand();
$ca_data = $command->queryAll();
based on yii2 guide for Operator Format
Operator format allows you to specify arbitrary conditions in a
programmatic way. It takes the following format:
[operator, operand1, operand2, ...] where the operands can each be
specified in string format, hash format or operator format
recursively, while the operator can be one of the following:
and: the operands should be concatenated together using AND. For
example, ['and', 'id=1', 'id=2']
so in your case should be
->where(['AND', 'ca.is_status = 0',
"ca.assessment_type = 'CONTINUOUS ASSESSMENT'",
"ca.ca_type = 'CONTINUOUS ASSESSMENT'"])
https://www.yiiframework.com/doc/guide/2.0/en/db-query-builder#operator-format
All you need is to remove AND from array passed to where():
->where([
'ca.is_status' => 0,
'ca.assessment_type' => 'CONTINUOUS ASSESSMENT',
'ca.ca_type' => 'CONTINUOUS ASSESSMENT'
])
If you pass associative array, it will be treated as pairs of column-value for conditions for WHERE in query. If you pass AND as first element, it is no longer a associative array, and query builder will ignore keys and only combine values as complete condition.
I am querying a database table conveniently named order and because of that I had to set 'quoteIdentifiers' => true in my app.php configuration. However, when I'm putting function names into the fields configuration of my find() call, CakePHP quotes them too.
$orders->find('all', array(
'fields' => array(
'DATE(Orders.date_added)',
'COUNT(*)',
),
'conditions' => array(
'Orders.order_status_id <>' => 0,
),
'group' => array(
'DATE(Orders.date_added)',
),
));
The query above ends up calling
SELECT <...>, `DATE(Orders.date_added)` FROM `order` <...>
which obviously throws an error.
I googled a lot, tried this:
$orders = $orders->find('all', array(
'conditions' => array(
'Orders.order_status_id <>' => 0,
),
'group' => array(
'DATE(Orders.date_added)',
),
))->select(function($exp) {
return $exp->count('*');
});
and that didn't work either, throwing me some array_combine error.
Is there any way for me to un-quote those function names, while keeping the rest of the query quoted automatically? Here's what I'm trying to accomplish:
SELECT <...>, DATE(Orders.date_added) FROM `order` <...>
Please help.
You should use function expressions, they will not be quoted, except for arguments that are explicitly being defined as identifiers:
$query = $orders->find();
$query
->select([
'date' => $query->func()->DATE([
'Orders.date_added' => 'identifier'
]),
'count' => $query->func()->count('*')
])
->where([
'Orders.order_status_id <>' => 0
])
->group([
$query->func()->DATE([
'Orders.date_added' => 'identifier'
])
]);
I'd generally suggest that you use expressions instead of passing raw SQL snippets wherever possible, it makes generating SQL more flexible, and more cross-schema compatible.
See also
Cookbook > Database Access & ORM > Query Builder > Using SQL Functions
I'm trying to query a page based on either a category ID or sub category name.
The variable $cat will either have an integer or varchar grabbed from my database.
I've been using cakephp 1.3 with a sql find all articles with a category of $cat OR sub-category LIKE $cat
It works great but a problem arises when $cat has a space between words, "google forms".
I've looked through this site and tried a number of methods with no luck. Appreciate any advice.
Here's my controller routines:
$cat = Sanitize::escape($cat);
$cat = trim($cat);
$title_a = str_replace($cat, "%".$cat."%", $cat);
$a_t = str_replace('"', $title_a, $title_a);
//var_dump($cat);
if(!empty($cat))
{
$sqlConditions = array('OR'=>array('Article.categories LIKE' => $a_t, 'Article.event_category_id' => $cat));
$sqlParams = array('conditions'=>$sqlConditions);
$catdata=$this->Article->find('all',$sqlParams);
return $catdata;
}
I've tried many different alternatives:
RLIKE instead of LIKE
Different query using MATCH
$sqlConditions = array(
'OR' => array(
'MATCH(Article.categories AGAINST(? IN BOOLEAN MODE)' => $cat,
'MATCH(Article.event_category_id) AGAINST(? IN BOOLEAN MODE)' => $cat
)
);
$sqlConditions = array('OR'=>array('Article.categories LIKE' => "%".$cat."%", 'Article.event_category_id' => $cat));
I think a decent solution would be to remove all of the spaces and make the characters of $cat lower case.
$likeCat = strtolower(str_replace(' ', '', trim($cat)));
$sqlConditions = array(
'OR'=> array(
'LOWER(REPLACE(Article.categories, ' ', ''))' => $likeCat,
'Article.event_category_id' => $cat
)
);
EDIT : I found the solution by replacing the SSP class by a customized SSP class I've found here : https://github.com/emran/ssp
I don't know if it's an understandable title, but here is my problem :
I have a DB-table (called projects) that needs to be inserted in a datatable. I've no problem to make a call using ServerSide and get results in the datatable.
But, for each project (each row), there is a project creator (column creator_id in the projects DB-table). What I need to do is to make a request to the creators DB-table in order to get the firstname/lastname of the creator, each time I get a row from the projects DB-table. Is that make sense?
Here is the code I use :
$table = 'projects';
$primaryKey = 'project_id';
$columns = array(
array(
'db' => 'project_id',
'dt' => 'DT_RowId',
'formatter' => function( $d, $row ) {
return $d;
}
),
array( 'db' => 'creator_id',
'dt' => 'creator',
'formatter' => function( $d, $row ) {
// Here I need to make a call to the creators DB-table and return the $creator_name value
return $creator_name;
}
)
);
// SQL server connection information
$sql_details = array(
'user' => '',
'pass' => '',
'db' => '',
'host' => ''
);
require(BASE_DIR.'/lib/dataTables/ssp.class.php');
$result = SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns);
You can use formatter property to make a separate SQL query but it will affect performance greatly by increasing script response time.
Instead you can use the following trick when using ssp.class.php with sub-queries instead of table name to use GROUP BY, JOIN, etc.
<?php
$table = <<<EOT
(
SELECT projects.project_id, creators.creator_id, creators.creator_name
FROM projects
LEFT JOIN creators ON projects.creator_id=creators.creator_id
) t
EOT;
$primaryKey = 'project_id';
$columns = array(
array(
'db' => 'project_id',
'dt' => 'DT_RowId'
),
array(
'db' => 'creator_id',
'dt' => 'creator'
),
array(
'db' => 'creator_name',
'dt' => 'creator_name'
)
);
// SQL server connection information
$sql_details = array(
'user' => '',
'pass' => '',
'db' => '',
'host' => ''
);
require(BASE_DIR.'/lib/dataTables/ssp.class.php');
$result = SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns);
echo json_encode($result);
To use that trick, you also need to edit ssp.class.php and replace all instances of FROM `$table` with FROM $table to remove backticks.
Alternatively, there is github.com/emran/ssp repository for library that extends ssp.class.php allowing GROUP BY, JOIN, aliases.
LINKS
See jQuery DataTables: Using WHERE, JOIN and GROUP BY with ssp.class.php for more information.
I'm performing a simple query that joins two tables together. What I get is something like this.
array(
[0] => array(
'id' => 52
'name' => 'charles',
'sale_id' => 921,
'sale_time' => 1306393996,
'sale_price' => 54.21
),
[1] => array(
'id' => 52
'name' => 'charles',
'sale_id' => 922,
'sale_time' => 1306395000,
'sale_price' => 32.41
),
...
);
...which is the expected result. However, I'd like the query to return something like this:
array(
[0] => array(
'id' => 52,
'name' => 'charles',
'sales' => array(
[0] => array(
'sale_id' => 921,
'sale_time' => 1306393996,
'sale_price' => 54.21
),
[1] => array(
'sale_id' => 922,
'sale_time' => 1306395000,
'sale_price' => 32.41
),
...
)
)
)
Now I realize I could simply perform two queries, one for the user info, and another for sales, and merge those arrays together using whatever language I'm using (PHP in this case). But I have many arrays of properties and querying and merging for those seems awfully inelegant to me (although it does work). It seems to me there'd be a way to work with a single, unified object without duplicating data.
Just wondering if there was a no-brainer query, or if that's simply not easy through MySQL alone.
I would say this is not possible with MySQL alone - you have to do some tricks at application level. That is, because even if you send a single query that will bring you all the data from MySQL to your application (PHP), they will come as a denormalized array of data - your first case.
If you want to get the data as in your second case, I'd recommend using some ORM - in Ruby there is ActiveRecord, in Perl there are Class::DBi, DBIx::Class and many more - I can not name one for PHP that is able to do this, but I am sure there are plenty.