Search code examples
phpactiverecordyii

Active Record Delete works false


I try to delete entries in the database with the active records of Yii. But I think it works really weird. I want to delete all records of my table where vehicle_id = the given id and plug_id NOT IN (given string)

I tried a lot of ways and nothing worked but this

$query = "delete from `vehicle_details` where `vehicle_id`= ".$vehicle->id." AND `plug_id` NOT IN (".implode(',', array_map(function($item) {
                                    return $item->type;
                                }, $vehicleDetails->plug)).")";
        $command = Yii::app()->db->createCommand($query);
        $command->execute();

But why isn't this working???

VehicleDetail::model()->DeleteAllByAttributes(
        array('vehicle_id' => $vehicle->id), 
        array('condition' => 'plug_id NOT IN (:ids)',
            'params' => array('ids' => implode(',', array_map(function($item) {
                                    return $item->type;
                                }, $vehicleDetails->plug)))));

Or this:

VehicleDetail::model()->deleteAll(' vehicle_id = :vehicleId AND plug_id NOT IN (:ids)', array('vehicleId' => $vehicle->id, 'ids' => implode(',', array_map(function($item) {
                                return $item->type;
                            }, $vehicleDetails->plug))));

But if I make and Find by attributes out of this query it works well and returns the correct data.

I hope you can explain it to me.


Solution

  • Your code does not work because of wrong arguments passed in the methods. Problems occur when YII tries to build CDbCriteria object using your array arguments. Fortunetly, you can build a CDbCriteria by yourself and pass it into methods directly. Guess in this particular case it will be easier to use a CDbCriteria object to solve the issue.

    $dbc = new CDbcriteria();
    $dbc->condition = 'vehicle_id = :vehicleId';
    $dbc->params = array(':vehicleId'=>$vehicle->id);
    $dbc->addNotInCondition(
        'plug_id', 
        array_map(
            function($item) {
                return $item->type;
            }, 
        $vehicleDetails->plug)
    );
    VehicleDetail::model()->deleteAll($dbc);
    

    That is all you need.