开发者

Symfony - I need to insert or update a record in database

开发者 https://www.devze.com 2023-03-20 00:36 出处:网络
The primary key is Id, but i want to check if already exists a record in db with same acronym, and if not, insert a new one, if exists, I need to do an update. I wrote this code, but it doesn\'t work.

The primary key is Id, but i want to check if already exists a record in db with same acronym, and if not, insert a new one, if exists, I need to do an update. I wrote this code, but it doesn't work. I receive this message from symfony "Integrity violation: 1062 Duplicate entry '180' for key 'PRIMARY'"

$id = Doctrine_Core::getTable('college')->findBy('acronym', 'PMM')->getFirst()->getId();
$college = new college();
$college->setId($id);
$college->setAcronym('PMM');
$college->setName('Paulo Miguel Mar');
$college->setUrl('www.pmm.com');
$college->save();

Anyone can help me? Thanks. Alexandre Sousa


I've tried the replace() solution, but I have some problems because I want to keep my id field. So I wanna do an update and not a replace.

I think save() should works, cause I read somewhere that this function is smart enough to do an update or insert. I still get this message: "Integrity violation: 1062 开发者_JS百科Duplicate entry '180' for key 'PRIMARY"

Anyone can help me?

Thanks.


The solution is dead simple, just use replace():

$college = new college();
$college
  ->setAcronym('PMM')
  ->setName('Paulo Miguel Mar')
  ->setUrl('www.pmm.com')
  ->replace()

This will work if and only if you have specified acronym as unique, of course.

0

精彩评论

暂无评论...
验证码 换一张
取 消