Search code examples
phporacle-databaseyiiyii-cactiverecord

$model->save() adding 'where id = 1' condition


I'm trying to update a model, I load the model, take all the data from the POST and then save it, easy... But my record was never updating so went to the log and discovered that the update query is adding a weird condition. FYI, MD_ID is my primary key.

So, I load the model, the next line is the SQL produced by Yii:

$model = Ositems::model()->findByPk($id);

SELECT * FROM "MTODETALLADO_INV" "t" WHERE "t"."MD_ID"=249217

If echo the json_encode of the loaded model I get that dictionary in my browser:

echo json_encode($model->getAttributes());

{""MD_BODEGA":"01","MD_PRODUCTO":"0031253","MD_CANTIDAD":"1","MD_PRECIOTOTAL":"1466",,"MD_PORCENTAJEDESCUENTO":"0","MD_IDCABECERA":"97403","MD_ID":"249217","MD_OBSERVACION":null}

At this point everything looks right, now I take the values from post:

$model->attributes = $_POST;

And here if echo the values of the model I get the new values right, now here is the problem: I save the model and this is the SQL Yii runs (I replaced the :yp_ values to make it more readable)

$model->save();

UPDATE "MTODETALLADO_INV" SET 

MD_BODEGA"='01'
MD_PRODUCTO"='0020514
MD_CANTIDAD"='10'
MD_PORCENTAJEDESCUENTO"='0
MD_IDCABECERA"=97403
MD_ID"=249218
MD_PRECIOTOTAL"='36210'
MD_OBSERVACION"=''

WHERE "MTODETALLADO_INV"."MD_ID"=1

And there is the problem! WHERE "MTODETALLADO_INV"."MD_ID"=1, Why would it make it 1 if all this time my model id has been 249218 ?

A few considerations: My model only takes some columns that I need from the actual table, Yii sets the other columns as null and I omitted them in the previous code. The table is in a foreign db, I use have a custom ActiveRecord which manages the CDbConnection to a database according to the user. (It's a webservice app)


Solution

  • I followed what the function save() did and could finally find the problem was when it tried to get the primary key. I had this method in my model:

    public function primaryKey()
        {
            return array('MS_ID');
        }
    }
    

    But it had to be:

    public function primaryKey()
        {
            return 'MS_ID';
        }
    }
    

    Somehow that was causing the problem.