Symfony: Control Model->save() function to perform INSERT or UPDATE

In Symfony Framework, Model->save() function is clever enough to determine to use INSERT or UPDATE for the query. But i’ve tried many ways to perform an UPDATE for my record but failed. It keep INSERT new record. Finally i found the solution to control the Model->save() function to perform INSERT or UPDATE.

Just a simple example:-
Assume there is a User table where ID is the primary key, and there is a user record with id = 5, now we perform the code below, it should be smart enough to perform UPDATE but NO!, the code below will INSERT a new record.


$user_id = 5;
$status = 1;

$user = new User();
$user->setId($user_id);
$user->setStatus($status);
$user->save(); // this will insert instead of update

Solution:


$user_id = 5;
$status = 1;

$user = new User();
$user->setNew(false); // u need to add this line
$user->setId($user_id);
$user->setStatus($status);
$user->save(); // now it will perform a UPDATE query

Special Thanks

Share and Enjoy:
  • Reddit
  • BlinkList
  • del.icio.us
  • Digg
  • Fark
  • IndianPad
  • StumbleUpon
  • YahooMyWeb


Posted at April 4th, 2008 by chua

If you think this article helps you to solve your problem and clear your headache, feel free to buy me a drink :)


Related Post

2 Responses to “Symfony: Control Model->save() function to perform INSERT or UPDATE”

  1. kyordanov Says:

    Very, very helpful! Thank you!

  2. yul Says:

    nice !
    thx a lot dude, I waisted about 2 hours on this issue before reading your tips.

Leave a Reply