【发布时间】:2020-07-13 19:44:08
【问题描述】:
我有一个 Symfony 5 项目,使用 symfony/api(API 平台)和一个带有 UniqueEntityconstraint 的实体(见下文。为了更好的易读性,我省略了字段注释,因为它们在这里不相关。):
/**
* @ORM\Entity(repositoryClass=CartItemRepository::class)
* @ApiResource(
* collectionOperations={"get","post"},
* itemOperations={"get","patch"},
* normalizationContext={"groups"={"cart_item:read"}}
* )
* @UniqueEntity(fields={"product","cart"})
*/
class CartItem
{
private $id;
private $product;
private $quantity;
private $cart;
/* ... */
}
假设我有一些数据:
----------------------------------------
| id | product_id | cart_id | quantity |
| 1 | 3 | 2 | 1 |
| 2 | 2 | 2 | 2 |
----------------------------------------
现在如果我发送这个 POST 请求:
{
"product": "/api/products/3",
"quantity": 1,
"cart": "/api/carts/2"
}
我当然会期待这个400 响应,因为插入这个条目会破坏[product_id,cart_id] 的唯一性,因为[3,2] 已经被ID 1 使用:
{
"@context": "/api/contexts/ConstraintViolationList",
"@type": "ConstraintViolationList",
"hydra:title": "An error occurred",
"hydra:description": "product: This value is already used.",
"violations": [
{
"propertyPath": "product",
"message": "This value is already used."
}
]
}
我的问题是:我是否有办法获取“重复”的实体的 IRI 或 ID?(这里,ID 应该是 1,即 IRI本来是/api/cart_items/1)。我想用这个实现的是重现 MySQL 的ON DUPLICATE KEY UPDATE quantity = quantity + :quantity 行为,通过检测这个错误并发送一个PATCH 请求,如果它发生,但是发送一个PATCH 请求,我需要 IRI,或者至少我要修补的项目的 ID。
编辑:
我在 Profiler 中看到这是可见的(请参阅下面的 cause 字段),但我无法获得 API 的响应...
Symfony\Component\Validator\ConstraintViolation {#2332 ▼
-message: "This value is already used."
-messageTemplate: "This value is already used."
-parameters: [▶]
-plural: null
-root: App\Entity\CartItem {#675 ▼
-id: null
-product: App\Entity\Product {#1888 …}
-quantity: 1
-cart: App\Entity\Cart {#2119 …}
}
-propertyPath: "product"
-invalidValue: App\Entity\Product {#1888 …}
-constraint: Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity {#2130 …}
-code: "23bd9dbf-6b9b-41cd-a99e-4844bcf3077f"
-cause: [▼
App\Entity\CartItem {#2330 ▼
-id: 2
-product: App\Entity\Product {#1888 …}
-quantity: 2
-cart: App\Entity\Cart {#2119 …}
}
]
}
【问题讨论】:
标签: php symfony api-platform.com