Please upgrade here. These earlier versions are no longer being updated and have security issues.
HackerOne users: Testing against this community violates our program's Terms of Service and will result in your bounty being denied.

Model->Save() primary key issue

edited February 2010 in Vanilla 2.0 - 2.8
I've just came across some problem with Model->Save() method.
I have a very simple table: (UserId, Name, Surname) with primary key UserId but without auto_increment option on it.
Now, when i try to save a model contains some data (1,John,Smith) using Model->Save() nothing hapens. After investigation I figured out what is wrong.
The method Save() tests whether it has to insert or update the data. It looks if provided data contains primary key value. If so, then it updates data instead of insert.
This causes my problem. I provide the UserId because it is required field and it's not auto_incremented, so Save method always tries to update table record which doesn't exists.
Maybe we should use something like this to check whether to insert or update:

$Insert = TRUE;
if($PrimaryKeyVal !== FALSE) {
$Result = $this->SQL
if($Result->NumRows() > 0) {
$Insert = FALSE;

Other problem with Save is that, I always get an error UserID is not a valid integer. Even if I add it like this $this->Form->AddHidden('UserID', 1); This is caused also by the Model's Save() method as it removes primary key from data set.


  • Options
    SS ✭✭
    edited February 2010
    To insert data with desired primary key (and skip model validation) you shoud use $Model->SQL->Insert($Table, $Data) or $Model->SQL->Replace($Table, $Data, $Where) (see code library\database\class.sqldriver.php), not $Model->Save()
  • Options
    But why do I have to skip validation? I want it to validate the data.
    I see that in for example Conversations this is done by overriding model's Save method. I'll do the same but I still wonder why isn't it handled by default? Performance or just skipped case?
Sign In or Register to comment.