【发布时间】:2020-01-15 13:17:13
【问题描述】:
我有一个包含图像数据的 SQLite 表。其中一列是position,它是一个文本字段,其中包含该图像应在站点上显示的位置。该字段具有唯一的约束。这是表定义:
CREATE TABLE images (id INTEGER PRIMARY KEY, title TEXT UNIQUE NOT NULL, position TEXT UNIQUE
NOT NULL, caption TEXT, filename TEXT, album INTEGER NOT NULL, publicationDate TEXT, updated
TEXT, createdBy INTEGER
NOT NULL, updatedBy INTEGER NOT NULL, FOREIGN KEY (createdBy) REFERENCES users(id), FOREIGN KEY
(album) REFERENCES albums(id), FOREIGN KEY (updatedBy) REFERENCES users(id));
并且,来自实体的相关位:
/**
* @ORM\Entity
* @ORM\Table(name="images",indexes={
* @Index(name="publication_date", columns={"publicationDate"})},
* uniqueConstraints={@UniqueConstraint(name="unique_position", columns={"position", "fileName"})}
* )
*/
class Image
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
**/
protected $id;
/**
* @ORM\Column(type="string", unique=true)
*/
protected $position;
除非position 列存在唯一约束违规,否则我可以成功写入表(Doctrine 持久化,然后刷新)。当存在唯一约束违规时,flush() 会静默失败(不写入数据库)并且应用程序继续执行。以下是相关代码 - 在设置和持久化实体之后:
try {
$this->entityManager->flush();
$message['type'] = 'alert-info';
$message['content'] = "$title added succesfully";
return $message;
} catch (UniqueConstraintViolationException $e) {
$message['type'] = 'alert-danger';
$message['content'] = "$title could not be added " . $e;
return $this->create($message, $formVars);
} catch (Exception $e) {
$message['type'] = 'alert-danger';
$message['content'] = "$title could not be added " . $e;
return $this->create($message, $formVars);
}
为什么我没有捕捉到异常?或者,根本就没有抛出?
【问题讨论】:
-
由于应用程序继续执行,所以根本不会抛出异常
-
如果它抛出异常,您是否尝试过不尝试捕获?
-
@B0re 是的。我很确定不会抛出异常。 Rain的上述评论似乎同意
-
老实说,我会采取不同的方法,并在“位置”字段上使用 @UniqueEntity symfony 约束,使用 ValidatorComponent 验证实体,然后根据结果刷新或创建捕获警报跨度>
标签: php sqlite exception doctrine-orm