I have a massive query that is generated using CDbCriteria as shown below:-
$schema = Yii::app()->db->schema;
$builder = $schema->commandBuilder;
// how to echo out this query?
$command = $builder->createFindCommand($schema->getTable('myuser'), $criteria);
$results = $command->queryAll();
I know I can use the 'logging' feature of Yii to view the query, is it possible to just echo out this single query (as opposed to having Yii show me tons of other queries that are being run on the page).
you can print query built by query builder by using $command->text.
In your example code will be:
$schema = Yii::app()->db->schema;
$builder = $schema->commandBuilder;
$criteria = new CDbCriteria();
$command = $builder->createFindCommand($schema->getTable('name_of_table'), $criteria);
$results = $command->text;
echo $results;
$command->text will return your complete query text
Add this in your config file. You can see the query and other details
at the bottom of the page.
'db'=>array(
'enableProfiling'=>true,
'enableParamLogging' => true,
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
…
array(
'class'=>'CProfileLogRoute',
'levels'=>'profile',
'enabled'=>true,
),
),
),
Related
I'm doing this:
$students = Student::find()->all();
return $this->render('process', array('students' => $students));
and then this in the view:
foreach($students as $student)
{
echo $student->name . ', ';
echo $student->getQuizActivitiesCount(); ?> <br /> <?php
}
i would like to see the sql query being performed. a student "has many" quiz activities, and the query performs perfectly, but i need to see the raw SQL. is this possible?
Method 1
With relations that return yii\db\ActiveQuery instance it's possible to extract the raw SQL query directly in code for example with var_dump().
For example if we have user relation:
/**
* #return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
You can then var_dump() the raw SQL like that:
var_dump($model->getUser()->prepare(Yii::$app->db->queryBuilder)->createCommand()->rawSql);
exit();
Note that you should call it like that and not $model->user->... (the latter returns User instance).
But in your case it's not possible because count() immediately returns int. You can var_dump() partial query without count(), but I think it's not convenient.
Note that you can use this method for dumping generated SQL of any ActiveQuery instances (not only those that were returned by relation), for example:
$query = User::find()->where(['status' => User::STATUS_ACTIVE]);
var_dump($query->prepare(Yii::$app->db->queryBuilder)->createCommand()->rawSql);
exit();
Method 2
This is much simpler in my opinion and I personally prefer this one when debugging SQL queries.
Yii 2 has built-in debug module. Just add this to your config:
'modules' => [
'debug' => [
'class' => 'yii\debug\Module',
],
],
Make sure you only have it locally and not on production. If needed, also change allowedIPs property.
This gives you functional panel at the bottom of the page. Find the DB word and click on either count or time. On this page you can view all executed queries and filter them.
I usually don't filter them in Grid and use standard browser search to quickly navigate through and find the necessary query (using the table name as keyword for example).
Method 3
Just make an error in query, for example in column name - cityy instead of city. This will result as database exception and then you can instantly see the generated query in error message.
If you want to log all relational queries of ActiveRecord in console application all proposed methods don't help. They show only main SQL on active record's table, \yii\debug\Module works only in browser.
Alternative method to get all executed SQL queries is to log them by adding specific FileTarget to configuration:
'log' => [
'targets' => [[
...
], [
'class' => 'yii\log\FileTarget',
'logFile' => '#runtime/logs/profile.log',
'logVars' => [],
'levels' => ['profile'],
'categories' => ['yii\db\Command::query'],
'prefix' => function($message) {
return '';
}
]]
]
UPDATE
In order to log insert/update/delete queries one should also add yii\db\Command::execute category:
'categories' => ['yii\db\Command::query', 'yii\db\Command::execute']
you can try this, assume you have a query given like:
$query = new Books::find()->where('author=2');
echo $query->createCommand()->sql;
or to get the SQL with all parameters included try:
$query->createCommand()->getRawSql()
In addition to arogachev answer, when you already work with an ActiveQuery object, here is the line I search to view the rawsql.
/* #var $studentQuery ActiveQuery */
$studentQuery = Student::Find();
// Construct the query as you want it
$studentQuery->where("status=3")->orderBy("grade ASC");
// Get the rawsql
var_dump($studentQuery->prepare(Yii::$app->db->queryBuilder)->createCommand()->rawSql);
// Run the query
$studentQuery->all();
when you have a query object you can also use
$query->createCommand()->getRawSql()
to return the Raw SQL with the parameters included or
$query->createCommand()->sql
which will output the Sql with parameters separately.
In order to log/track every/all queries:
extend \yii\db\Connection and override createCommand method, like below:
namespace app\base;
class Connection extends \yii\db\Connection {
public function createCommand($sql = null, $params = array()) {
$createCommand = parent::createCommand($sql, $params);
$rawSql = $createCommand->getRawSql();
// ########### $rawSql -> LOG IT / OR DO ANYTHING YOU WANT WITH IT
return $createCommand;
}
}
Then, simply change your db connection in your db config like below:
'db' => [
'class' => 'app\base\Connection', // #### HERE
'dsn' => 'pgsql:host=localhost;dbname=dbname',
'username' => 'uname',
'password' => 'pwd',
'charset' => 'utf8',
],
Now, you can track/read/... all queries executed by db connection.
Try like,
$query = Yii::$app->db->createCommand()
->update('table_name', ['title' => 'MyTitle'],['id' => '1']);
var_dump($query->getRawSql()); die();
$query->execute();
Output:
string 'UPDATE `table_name`
SET `title`='MyTitle' WHERE `id`='1'
' (length=204)
I've recently added a custom column to my CGridView using the yii's get method to create a virtual attribute. The virtual attribute that I've created looks like this and works as expected.
public function getNumIndv()
{
// gets the id of the current list
$list_id = $this->id;
// returns the number of recipients with that list id
return $count = Recipient::model()->count(array("condition"=>"list_id = $list_id"));
}
From there in my GridView I added the custom column "numindv" like so
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'paylist-grid',
'dataProvider'=>$dataProvider,
'filter'=>$model,
'columns'=>array(
'name',
'numindv',
'balance',
'due_date',
/*
'status',
*/
array(
'class'=>'CButtonColumn',
'template'=>'{Manage}',
'buttons'=>array
(
'Manage' => array
(
'label'=>'Manage',
'url'=>'Yii::app()->createUrl("recipient/index", array("id"=>$data->id))',
),
)
),
),
)); ?>
This works as expected - almost. When the user views the form they see three columns "name, balance, and due-date" not lit up. As well, if you click on them they light up and are sorted.
for numindv however, the column is automatically lit up and does not allow individuals to click on it to change the order. Is there something simple that I'm missing here? Why is my grid view treating my virtual column different from the rest?
You cant use sorting in CActiveDataProvider by custom column.
You can make numindv column header link by using this approach:
$sort = new CSort();
$sort->attributes = array(
'numindv' => 'numindv',
'*' // all other columns
);
$dataProvider->sort = $sort;
But you still do not get the desired result, because when you click on the this sorting link it name will be added in SQL query:
SELECT * FROM `recipient` `t` ORDER BY `t`.`numindv`...
But your table is no column numindv.
I advise you to use a CArrayDataProvider.
UPD:
You can set sql rules for this sorting:
$sort->attributes = array(
'numindv' => array(
'asc'=>"numindv asc",
'desc'=>"numindv desc",
),
'*' // all other columns
);
And in Recipient::search() method you should add this line:
$criteria->select .= ', (/*any SQL request to retrieve the numindv value*/) as numindv';
I essentially want to search the database using an array of barcodes. Here is my query if I only have one barcode:
$q = new CDbCriteria(array(
'condition' => '"barcode" = :barcode',
'params' => array(':barcode' => $this->barcode),
));
I am trying to modify this query so that I query an array of barcodes. It would be a fairly standard array, something like ['Barcode1','Barcode2', 'Barcode3'].
How can I modify this query I have to instead return the results for Barcode1 OR Barcode2 OR Barcode3?
You need to add an inCondition
http://www.yiiframework.com/doc/api/1.1/CDbCriteria#addInCondition-detail
something like this
$q = new CDbCriteria();
$q->addInCondition("barcode",array("value1","value2"...),"AND");
I have a website on Yii Framework and I want to search a table for matching words.
I keep getting "out of memory" (it is a large table).
I try this code but it keeps loading the page
$dataProvider = new CActiveDataProvider('Data');
$iterator = new CDataProviderIterator($dataProvider);
foreach($iterator as $data) {
echo $data->name."\n";
}
So I try this code but it keeps limiting the result to 10:
$dataProvider = new CActiveDataProvider('Data');
$iterator = new CDataProviderIterator($dataProvider);
foreach($dataProvider as $data) {
echo $data->name."\n";
}
and if I do this I get the "out of memory" message:
$dataProvider = new CActiveDataProvider('Data' array(
'criteria'=>array(
'order'=>'id DESC',
),
'pagination' => false
));
foreach($dataProvider as $data) {
echo $data->name."\n";
}
I don't know why are you need to load all search results in one page, but you can change number of items per page to desire value by this code (and using pagination):
$dataProvider = new CActiveDataProvider('Data' array(
'criteria'=>array(
'order'=>'id DESC',
'condition' => 'town LIKE :search_town AND FK_country > :country_id',
'params' => array(':search_town' => $search_town.'%', ':country_id' => 10)
),
'pagination' => array(
"pageSize" => 100,
//"currentPage" => 0, //using for pagination
)
));
$iterator = new CDataProviderIterator($dataProvider);
foreach($iterator as $data) {
echo $data->name."\n";
}
Here http://sonsonz.wordpress.com/2011/10/14/yii-examples-of-using-cdbcriteria/ more examples
It is unwise to use CActiveDataProvider for big datasets. Especially if you only want to perform background tasks on them.
It would be advised to use direct SQL and go from there.
Based on the comments on CreatoR's answer, you are trying to find a number of occurences in a big table. As an example:
$connection=Yii::app()->db;
$sql = "SELECT id FROM data WHERE field1 LIKE '%someValue%' OR field2 LIKE '%someValue%' OR field3 LIKE '%someValue%'";
$command=$connection->createCommand($sql);
$numberOfRestuls=$command->execute();
//if you also want to display the results :
$ids=$command->queryAll();
$criteria=new CDbCriteria;
$criteria->addInCondition('id',$ids,'OR');
$dataProvider = new CActiveDataProvider('Data', $criteria);
//etc
I'm using CakePHP 1.3.8, and I've installed the CakeDC Search plugin. I have a Tutorial model, which is in a HABTM relationship with a LearningGoal model.
I have a search action & view in the Tutorials controller with which I can successfully search fields in the Tutorial model. I'd also like to filter my tutorial search results using LearningGoal checkboxes on the same form. I've tried adding various parameters to Tutorial's $filterArgs and TutorialsController's $presetVars. I've also tried moving the relevant $filterArgs to the LearningGoal model. I have not yet been able to successfully trigger the entry for learning goals in $filterArgs.
I think I must be missing something obvious. Or maybe the Search plugin doesn't support what I'm trying to do. Does anyone know how to use this plugin to search on associated models?
So here's what I've figured out. You can combine what's below with the Search plugin directions to search on related models.
The $filterArgs piece in the Tutorial model must look like this:
var $filterArgs = array(
array('name' => 'LearningGoal', 'type' => 'subquery', 'method' => 'findByLearningGoals', 'field' => 'Tutorial.id'),
);
Here's the supporting function in the Tutorial model:
function findByLearningGoals($data = array()) {
$ids = explode('|', $data['LearningGoal']);
$ids = join(',', $ids);
$this->LearningGoalsTutorial->Behaviors->attach('Containable', array('autoFields' => false));
$this->LearningGoalsTutorial->Behaviors->attach('Search.Searchable');
$query = $this->LearningGoalsTutorial->getQuery('all',
array(
'conditions' => array('LearningGoalsTutorial.learning_goal_id IN (' . $ids . ')'),
'fields' => array('tutorial_id'),
)
);
return $query;
}
In TutorialsController, $presetVars should look like this:
public $presetVars = array(
array('field' => 'LearningGoal', 'type' => 'checkbox', 'model' => 'Tutorial'),
);
And in my search action in TutorialsController, I did this:
$this->LearningGoal = $this->Tutorial->LearningGoal;
The Prg component seems to need that.
I am using CakePHP version 2.X
Every time I come to do this in a project I always spend hours figuring out how to do it using CakeDC search behavior so I wrote this to try and remind myself with simple language what I need to do. I've also noticed that although Michael is generally correct there is no explanation which makes it more difficult to modify it to one's own project.
When you have a "has and belongs to many" relationship and you are wanting to search the joining table i.e. the table that has the two fields in it that joins the tables on either side of it together in a many-to-many relationship you want to create a subquery with a list of IDs from one of the tables in the relationship. The IDs from the table on the other side of the relationship are going to be checked to see if they are in that record and if they are then the record in the main table is going to be selected.
In this following example
SELECT Handover.id, Handover.title, Handover.description
FROM handovers AS Handover
WHERE Handover.id in
(SELECT ArosHandover.handover_id
FROM aros_handovers AS ArosHandover
WHERE ArosHandover.aro_id IN (3) AND ArosHandover.deleted != '1')
LIMIT 20
all the records from ArosHandover will be selected if they have an aro_id of 3 then the Handover.id is used to decide which Handover records to select.
On to how to do this with the CakeDC search behaviour.
Firstly, place the field into the search form:
echo $this->Form->create('Handover', array('class' => 'form-horizontal'));?>
echo $this->Form->input('aro_id', array('options' => $roles, 'multiple' => true, 'label' => __('For', true), 'div' => false, true));
etc...
notice that I have not placed the form element in the ArosHandover data space; another way of saying this is that when the form request is sent the field aro_id will be placed under the array called Handover.
In the model under the variable $filterArgs:
'aro_id' => array('name' => 'aro_id', 'type' => 'subquery', 'method' => 'findByAros', 'field' => 'Handover.id')
notice that the type is 'subquery' as I mentioned above you need to create a subquery in order to be able to find the appropriate records and by setting the type to subquery you are telling CakeDC to create a subquery snippet of SQL. The method is the function name that are going to write the code under. The field element is the name of the field which is going to appear in this part of the example query above
WHERE Handover.id in
Then you write the function that will return the subquery:
function findByAros($data = array())
{
$ids = ''; //you need to make a comma separated list of the aro_ids that are going to be checked
foreach($data['aro_id'] as $k => $v)
{
$ids .= $v . ', ';
}
if($ids != '')
{
$ids = rtrim($ids, ', ');
}
//you only need to have these two lines in if you have not already attached the behaviours in the ArosHandover model file
$this->ArosHandover->Behaviors->attach('Containable', array('autoFields' => false));
$this->ArosHandover->Behaviors->attach('Search.Searchable');
$query = $this->ArosHandover->getQuery('all',
array(
'conditions' => array('ArosHandover.aro_id IN (' . $ids . ')'),
'fields' => array('handover_id'), //the other field that you need to check against, it's the other side of the many-to-many relationship
'contain' => false //place this in if you just want to have the ArosHandover table data included
)
);
return $query;
}
In the Handovers controller:
public $components = array('Search.Prg', 'Paginator'); //you can also place this into AppController
public $presetVars = true; //using $filterArgs in the model configuration
public $paginate = array(); //declare this so that you can change it
// this is the snippet of the search form processing
public function admin_find()
{
$this->set('title_for_layout','Find handovers');
$this->Prg->commonProcess();
if(isset($this->passedArgs) && !empty($this->passedArgs))
{//the following line passes the conditions into the Paginator component
$this->Paginator->settings = array('conditions' => $this->Handover->parseCriteria($this->passedArgs));
$handovers = $this->Paginator->paginate(); // this gets the data
$this->set('handovers', $handovers); // this passes it to the template
If you want any further explanation as to why I have done something, ask and if I get an email to tell me that you have asked I will give an answer if I am able to.