Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

验证器unique复杂条件验证的问题 #2577

Open
tlerbao opened this issue Aug 17, 2021 · 1 comment · May be fixed by #2893
Open

验证器unique复杂条件验证的问题 #2577

tlerbao opened this issue Aug 17, 2021 · 1 comment · May be fixed by #2893
Labels

Comments

@tlerbao
Copy link

tlerbao commented Aug 17, 2021

根据下图手册的写法,会报错 not support data:district_id=1,是本菜使用姿势不对,还是bug了?

class Community extends Validate
{
    protected $rule = [
        'district_id|所属区域' => 'require',
        'name'   => 'unique:system_community,district_id=1',
    ];
}

image

@big-dream
Copy link
Contributor

@liu21st 使用 6.1.4 版本测试和查阅代码,发现确实不支持 'unique:user,status=1&account='.$data['account'] 这种写法,手册需要删除这种用法?

/**
* 验证是否唯一
* @access public
* @param mixed $value 字段值
* @param mixed $rule 验证规则 格式:数据表,字段名,排除ID,主键名
* @param array $data 数据
* @param string $field 验证字段名
* @return bool
*/
public function unique($value, $rule, array $data = [], string $field = ''): bool
{
if (is_string($rule)) {
$rule = explode(',', $rule);
}
if (str_contains($rule[0], '\\')) {
// 指定模型类
$db = new $rule[0];
} else {
$db = $this->db->name($rule[0]);
}
$key = $rule[1] ?? $field;
$map = [];
if (str_contains($key, '^')) {
// 支持多个字段验证
$fields = explode('^', $key);
foreach ($fields as $key) {
if (isset($data[$key])) {
$map[] = [$key, '=', $data[$key]];
}
}
} elseif (isset($data[$field])) {
$map[] = [$key, '=', $data[$field]];
} else {
$map = [];
}
$pk = !empty($rule[3]) ? $rule[3] : $db->getPk();
if (is_string($pk)) {
if (isset($rule[2])) {
$map[] = [$pk, '<>', $rule[2]];
} elseif (isset($data[$pk])) {
$map[] = [$pk, '<>', $data[$pk]];
}
}
if ($db->where($map)->field($pk)->find()) {
return false;
}
return true;
}

测试代码:

<?php
namespace app\validate;

use think\Validate;

class Test extends Validate
{
    protected $rule = [
        'district_id|所属区域' => 'require',
        'name'                => 'unique:system_community,district_id=1&name=2'
    ];
}
<?php
namespace app\controller;

use app\BaseController;
use app\validate\Test;

class Index extends BaseController
{
    public function index()
    {
        $validate = validate(Test::class)->check([
            'district_id' => '1',
            'name'        => 'zs',
        ]);
        dump($validate);
    }
}

@big-dream big-dream added bug and removed wontfix labels Mar 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants