0

I have a problem with Yii's CDBCrtieria builder. I am trying to make a rather complex query while using the escaping and safe functions provided by PDO.

Here is the query I am basically trying to build:

SELECT * FROM tbl_audit_log 
    WHERE (model_id = 1 AND model = "Title") OR 
          (model_id = 1 AND model = "Product") //etc

This is being built dynamically in PHP like:

$model_ids = array(array($model->id, 'Title'));
foreach($model->products as $id => $product){
    $model_ids[][] = $product->id;
    $model_ids[][] = "Product";
}

So I don't know the values of the WHERE before I build the query. I must find an easy way to build:

    WHERE (model_id = 1 AND model = "Title") OR 
          (model_id = 1 AND model = "Product") //etc

Dynamically.

I have looked through the documentation but the closest thing I see is addCondition which would require complex coding to get working properly.

Does Yii provide any easy way of achieving this without having to deal with writing complex code to name my params etc?

4

1 回答 1

3

It is indeed a bit more complex, but here's a working solution:

$criteria = new CDbCriteria();
$param_id = 0;
// $model_ids is the one you built in your original code
foreach( $model_ids as $id_pair ) {
    $criteria->addCondition( '( model_id = :id' . $param_id . ' AND model = :model' . $param_id . ' )', 'OR' );
    $criteria->params[ ':id' . $param_id ] = $id_pair[0];
    $criteria->params[ ':model' . $param_id ] = $id_pair[1];
    $param_id++;
}

This will generate custom identifiers for each of your parameters so they will all be validated. Then you can just use $criteria in your query.

于 2012-08-24T17:11:12.610 回答