How to get last executed query Yii - yii

How to get Last executed query after model save, update, delete in yii.
i.e:
$model->save();
like $this->db->last_query(); in CI
Thanks

Put this on your config.php file , you can see other details along with your query ...
'db'=>array(
'enableProfiling'=>true,
'enableParamLogging' => true,
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
…
array(
'class'=>'CProfileLogRoute',
'levels'=>'profile',
'enabled'=>true,
),
),
),

The simplest way to show last executed query is to make an sql error in that query! :p Give an invalid column name in query, then Yii error reporting will show that query as error, but you can see that query.

Related

Yii dropDownList nested conditions (not nested dropDown)

in a dropdown I would like to find data in 2 levels. Maybe my logic is wrong, but as I remember I have done such things before, the only difference was that I got always 1 simple result back, but now, I should handle an array. Here's my code:
echo $form->dropDownList($model, 'szeriaGyartmanyId', GxHtml::listDataEx(
SzeriaGyartmany::model()->findAllAttributes(
null, true, 'rajz_osszetett_technologia_id IN (:rajz_osszetett_technologia_id) AND keszDb<db', array(
':rajz_osszetett_technologia_id' => RajzOsszetettTechnologia::model()->findAllAttributes(
null, true, 'osszetett_technologia_id = :osszetett_technologia_id', array(
':osszetett_technologia_id' => OsszetettTechnologia::model()->find("name='Horganyzás alatt'")->id
)
)->id
)
)
), array('style' => 'width: auto', 'prompt' => ''));
the core gives back one single ID, it's no problem, but the second level gives back an array (or array of objects? I'm not sure). The point is, is it possible here somehow to implode resulting rajz_osszetett_technologia_ids, or do I have to do completely differently? I've tried to implode it right in place, but I got an error: Argument must be an array. So that's why I guess the result is an array of objects.
Is it clear what I would like to achieve? For me it seems kinda obvious to do it somehow like this, but maybe my logic is completely wrong. Can somebody please point me to the right direction?
Thanks a lot!
BR
c
GxActiveRecord::findAllAttributes(null,true..) returns an array of objects with only the required properties set. In order to obtain an array of ids as required you need to wrap it in GxHtml::listDataEx() and then use array_keys to obtain only the keys.
echo $form->dropDownList($model, 'szeriaGyartmanyId', GxHtml::listDataEx(
....
':rajz_osszetett_technologia_id' => implode(',',
array_keys(
GxHtml::listDataEx(
RajzOsszetettTechnologia::model()->findAllAttributes(
....
)
)
)
)
....
)
Perhaps a custom query would be easier and clearer than this.

Get results of SQL Query as string in Rails

when i run a complicated sql query from the command line like this
sqlite3 db/development.sqlite3 < queries.sql
i get a result like this
Competency Name|Component Name|3.77|4.0|0.23
Another Competency Name|Another Component Name|3.77|4.0|0.23
which i can easily parse like this
hidden_strengh_strings = results.split("\n")[1..-1];
hidden_strengh_strings.each do |hidden_strength_string|
hidden_strengh_values = hidden_strength_string.split("|");
hidden_strength = {}
hidden_strength.merge!(:competency => hidden_strengh_values[0]);
hidden_strength.merge!(:component => hidden_strengh_values[1]);
hidden_strength.merge!(:reviewer_average_score => hidden_strengh_values[2]);
hidden_strength.merge!(:reviewee_average_score => hidden_strengh_values[3]);
hidden_strength.merge!(:exceedance => hidden_strengh_values[4]);
hidden_strengths << hidden_strength
end
but i have no idea how to get these results from within ActiveRecord.
results = ActiveRecord::Base.connection.execute(File.open(Rails.root.join('queries.sql'), 'r') { |f| f.read } );
doesn't seem to do what i want it to.
i'd be happy to take any approach to solve this problem. even rewriting the sql from within the ActiveRecord DSL. but i need help finding the right direction.
thanks : )
Nishant lead me to the solution.
ActiveRecord::Base.connection.execute
Works fine its just that the query started with:
select 'HIDDEN STRENGTHS';
so exec ended at the semicolon.
Thanks!

cakephp array's and find statement

I have two find statements and need the results of one find statement to use in the second find statement however the two methods I have tried to use have come back with errors
here is the first find statement, it lists the sender_id's
$sender=$this->Invoice->Find('list', array('fields'=>('sender_id')));
here is the second find statement, it takes that list of sender_id's and returns the corresponding company_name
$senderName=$this->Account->Find('all', array(
'conditions' => array(
$sender=>'account.id')));
this returns the right information however returns this error Warning (2): Illegal offset type [APP\Controller\InvoicesController.php, line 185]
so i tried doing it this way
$senderName=$this->Account->Find('all', array(
'conditions' => array(
'id'=>$sender['Invoice']['sender_id'])));
and get an undefined index on invoice.
$senderName=$this->Account->Find('all', array(
'conditions' => array(
'Account.id' => array_values($sender),
),
));
The key is the field and the value is, well, the value(s).

How show all queries to database in yii framework

In CodeIgniter I would do:
print_r ($this->db->queries);
In Yii I tried:
print_r (Yii::app()->db)
But this doesn't show any queries.
UPDATE:
I understand my problem: when I want to show db queries on a POST action, I don't show it. When using GET, it's ok.
As #bool.dev said, you can use CWebLogRoute or in my case i use CFileLogRoute to store these queries in file.
array (
'class' => 'CFileLogRoute',
'categories' => 'system.db.*',
'logFile' => 'sql.log',
),
To complement #snippLeaf-com's answer, you can trace this file filtering by the keywords you want like this:
// filter by "INSERT" or "UPDATE"
$ tail -f /path_to/protected/runtime/sql.log |grep 'INSERT\|UPDATE'
// filter (case insensitive) by "SELECT" in table "x2_users"
$ tail -f /path_to/protected/runtime/sql.log |grep -i SELECT.*x2_users
OBS: to get fresh data you could need refresh database cache:
rm -f protected/runtime/cache/*.bin
If you really want every query log in yii use yii db profiler extension.
Step1. Download extension from --> link
Step2. Unpack to protected/extensions/
Step3. Rename folder name yii-db-profiler-master to db_profiler
Step4. Update the following to your protected/config/main.php:
<?php
return array(
// …
'components' => array(
// …
'db' => array(
// …
'enableProfiling'=>true,
'enableParamLogging' => true,
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
// …
array(
'class'=>'ext.db_profiler.DbProfileLogRoute',
'countLimit' => 1, // How many times the same query should be executed to be considered inefficient
'slowQueryMin' => 0.01, // Minimum time for the query to be slow
),
),
),
),
);

Getting the string representation from CDbCriteria

Is there any way to the get the string representation of the query from CDbCriteria? For testing and debugging purposes.
You can use logging and profiling configuring your main.php like this:
'components'=>array(
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CWebLogRoute',
'categories'=>'system.db.CDbCommand',
'showInFireBug'=>true,
),
),
),
'db'=>array(
'enableProfiling'=>true,
'enableParamLogging'=>true,
),
),
I spend a lot amount of time for finding the answer to this question, so thought of sharing it with you guys. Hope this saves your precious time.
As mentioned by Jon above: CDbCriteria does not aggregate enough information to construct the full query, you have to use the model class information also on which you will put the query constraints.
As the example given in Yii docs for CDbCriteria; this is how basically you use it-
$criteria=new CDbCriteria();
$criteria->compare('status',Post::STATUS_ACTIVE);
$criteria->addInCondition('id',array(1,2,3,4,5,6));
$posts = Post::model()->findAll($criteria);
Here Post is the name of the model on which you execute the query condition.
So if you want to get the text representation of the query written in CDbCriteria, you have to involve the model information also i.e. Post.
This is how you can do it -
$model = new Post();
$query = $model->getCommandBuilder()->createFindCommand($model->getTableSchema(), $criteria)->getText();
When you print the value in $query variable it prints the raw query.
Hope this helps.