Yii 1, get SQL generated by CDbCriteria

7.1k views Asked by At

got a problem, I need to get all ids of models (not only visible but all models) in CGridView. For that I use its DataProvider - get a criteria from it and pass it to command builder

$criteria = $dataProvider->getCriteria();
$criteria->select = 'id';
$command = Y::db()->commandBuilder->createFindCommand('tableName', $criteria);
$ids = $command->queryColumn();

It is working fine until we got filtering via related tables. For example user adds a number to a filter of the grid - "House Number" = 24. When it happens related table - "address" adds to $criteria->with and "address.home_number = 24" adds to $criteria->condition.

ActiveRecord automatically parses the "with" property of criteria and apply joins, so our condition would be fine with it, but CommandBuilder - not. I can't use AR for it, since it is deadly slow. I must use Builder, but I can't make joins, there could be more than 20 filters applied.

If I could get SQL generated by AR and then pass it to Builder - it would be great.

1

There are 1 answers

4
Link Link On

After some research I've created custom class ActiveFinder - copy of CActiveFinder class of Yii framework. So you can just pass model you are gonna search and the criteria in new static method:

$model = new User();
$criteria = new CDbCriteria();
$criteria->select = 't.id';
$command = ActiveFinder::getCommand($model, $criteria);
// $command variable have the SQL text
$sql = $command->text;

here you can grab the class - https://github.com/LinGG/ActiveFinder