验证整数数组 [英] Validate an array of integers

查看:95
本文介绍了验证整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个整数数组:

[1, 2, 3, 4, ...]

如何使用验证器检查表中是否存在每个验证器?可能没有foreach循环吗?

How can I use the validator to check if each of these exists in a table? Possible without a foreach loop?

$validator = Validator::make($request->all(), [
    'array' => 'required|exists:users,id'
]);

推荐答案

您的书面验证应可以工作.如果将现存验证与数组一起使用,它将自动将where in用于现存查询.

Your validation as written should work. If the exists validation is used with an array, it will automatically use where in for the exists query.

因此,根据您所编写的验证,验证将获得users记录的计数,其中id字段位于array输入提供的ID列表中.

So, given your validation as you have written, the validation will get the count of the users records where the id field is in the list of ids provided by your array input.

因此,如果您的array[1, 2, 3, 4],它将在users.id in (1,2,3,4)处获得计数,并将其与array数组中元素的计数(为4)进行比较.如果查询计数大于等于数组计数,则验证通过.

Therefore, if your array is [1, 2, 3, 4], it will get the count where users.id in (1,2,3,4), and compare that to the count of the elements in your array array (which is 4). If the query count is >= the array count, validation passes.

这里要注意两件事:如果您要检查的列不是唯一的,或者您的数组数据具有重复的元素.

Two things to be careful about here: if the column you're checking is not unique, or if your array data has duplicate elements.

如果您要检查的列不是唯一的,则您的查询计数可能会> =数组计数,但并非数组中的所有ID实际上都存在.如果您的数组是[1, 2, 3, 4],但是您的表中有4条ID为1的记录,即使ID 2、3和4的记录不存在,验证也会通过.

If the column you're checking is not unique, it's possible your query count will be >= the array count, but not all ids from your array actually exist. If your array is [1, 2, 3, 4], but your table has four records with id 1, validation will pass even though records with ids 2, 3, and 4 don't exist.

对于重复的数组值,如果您的数组是[1, 1],但是您只有一条ID为1的记录,则验证将失败,因为查询计数将为1,但您的数组计数为2.

For duplicate array values, if your array was [1, 1], but you only have one record with an id of 1, validation would fail because the query count will be 1, but your array count is 2.

要解决这两个警告,可以进行单个数组元素验证.您的规则如下所示:

To work around these two caveats, you can do individual array element validation. Your rules would look something like:

$request = [
    'ids' => [1, 2, 3, 4],
];

$rules = [
    'ids' => 'required|array',
    'ids.*' => 'exists:users,id', // check each item in the array
];

$validator = Validator::make($request, $rules);

dd($validator->passes(), $validator->messages()->toArray());

请记住,每个元素将单独进行验证,因此它将对ids数组中的每个元素运行新查询.

Keep in mind that each element will be validated individually, so it will run a new query for each element in the ids array.

这篇关于验证整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆