use*_*101 6 php mysql doctrine symfony1 symfony-1.4
我有一张桌子
CREATE TABLE `sob_tags_articles` (
`tag_id` int(11) NOT NULL,
`article_id` int(11) NOT NULL,
`id` int(11) NOT NULL auto_increment,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=112
Run Code Online (Sandbox Code Playgroud)
和使用Doctrine保存对象的方法:
$sbTagsArticles = new SobTagsArticles();
$sbTagsArticles->article_id = $pubId;
$sbTagsArticles->tag_id = $tagId;
$sbTagsArticles->save();
Run Code Online (Sandbox Code Playgroud)
但是如果记录存在同一个$ pubId和$ tagId,则新记录将插入新PK.
如何用symfony INSERT IGNORE进入表?
$sbTagsArticles->isNew();
Run Code Online (Sandbox Code Playgroud)
返回1.
日Thnx.
pro*_*son 13
try
{
$record->save();
}
catch(Doctrine_Exception $e)
{
if($e->getErrorCode() !== $duplicateKeyCode)
{
/**
* if its not the error code for a duplicate key
* value then rethrow the exception
*/
throw $e;
}
/**
* you might want to fetch the real record here instead
* so yure working with the persisted copy
*/
}
Run Code Online (Sandbox Code Playgroud)
您应该确保在应用程序端而不是SQL端存在相同的记录.如果您不希望存在相同的文章/标记组合,则添加唯一索引(article_id, tag_id).这应该会产生一个mysql错误,这个错误反过来会产生一个你可以捕获的学说异常.没有用于保存的忽略标志...您可以使用在DBAL的较低级别(Doctrine_Query,Doctrine_Connection等)运行的标志,但不能从ORM层直接运行.
Doctrine_Record::isNew() 如果你已经实例化了将其从数据库中拉出来的记录,那么它将永远返回true,否则它无法知道该记录是不是新的.
另外你为什么要使用MyISAM存储引擎?我很确定这会在使用Doctrine时产生更多的开销,因为它需要在php端模拟约束.通常,您的架构看起来像这样:
CREATE TABLE `sob_tags_articles` (
`tag_id` int(11) NOT NULL,
`article_id` int(11) NOT NULL,
`id` int(11) NOT NULL auto_increment,
PRIMARY KEY (`id`),
CONSTRAINT `some_unique_constraint_name_1`
FOREIGN KEY `article_id`
REFERENCES `article` (`id`)
ON DELETE CASCADE,
CONSTRAINT `some_unique_constraint_name_2`
FOREIGN KEY `tag_id`
REFERENCES `tag` (`id`)
ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=112
Run Code Online (Sandbox Code Playgroud)
这是要使用的实际代码
try
{
$record->save();
}
catch(Doctrine_Connection_Exception $e)
{
if($e->getPortableCode() != Doctrine::ERR_ALREADY_EXISTS)
{
/**
* if its not the error code for a duplicate key
* value then rethrow the exception
*/
throw $e;
}
/**
* you might want to fetch the real record here instead
* so yure working with the persisted copy
*/
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11875 次 |
| 最近记录: |