UpdateEntityRequest.php:
'phones' => 'sometimes|nullable|array',
'phones.*.id' => 'sometimes|required|integer|distinct|exists:entity_phones,id,entity_id,'.$this->id,
'phones.*.number' => 'required|alpha_num|max:255|distinct|unique:entity_phones,number,'.$this->id.',entity_id',
entity_phones 表:
id, number, entity_id.
unique constraint: (number, entity_id)
EntityRepository.php:
foreach ($attributes['phones'] as $phone) {
if (isset($phone['id'])) {
$entity->phones()->updateOrCreate([
'id' => $phone['id'],
'entity_id' => $entity->id
], $phone);
} else {
$entity->phones()->create($phone);
}
}
我的实体可以关联多个电话号码,但不能关联重复的号码。我的目的是检查 UpdateEntityRequest.php 中的唯一(entity_id,number),因此:
- 如果电话对象没有 ID,则应检查号码、entity_id 的组合是否不存在。但该号码可以与其他entity_id共存。
- 如果请求带有 id,则应检查数字、entity_id 的组合是否仅存在于其他 id 中,但忽略给定的 id。
仅当我希望 Laravel Unique 规则进行验证时,我才对其进行验证时遇到问题。任何我如何制定此解决方案的想法将不胜感激。
最佳答案
如果您需要在唯一检查期间忽略给定 ID,请尝试使用 Rule 类来流畅地定义规则。
use Illuminate\Validation\Rule;
Validator::make($request_data, [
'number' => [
'required',
'alpha_num', (...all your other rules)
Rule::unique('entity_phones')->ignore($entity_id),
],
]);
您可以在 laravel 文档中阅读有关 unique rule 的更多信息在段落中:强制唯一规则忽略给定 ID。
关于php - 如何使 Laravel 对输入数组进行唯一验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64847443/