Laravel 强制执行唯一组合的验证规则?

Laravel validation rule to enforce unique combinations?

我在同一个 table 中有两列 A 和 B。 B 列只能接受 A 列的每个值的唯一值。

column A column B
1 8
1 52
1 8 not allowed because value 8 in Column B has already been set for value 1 in column A
2 78
2 2
2 78 not allowed because value 78 in Column B has already been set for value 2 in column A

等...

我正在尝试编写可以执行此验证的验证规则,但我遇到了问题。

这很容易通过添加到 unique rule 的闭包来完成。假设您正在使用表单请求验证:

public function rules(): array
{
    return [
        'A' => [
            Rule::unique('table')->where(function ($query) {
                $query->where('B', $this->B);
            }),
        ],
    ];
}

如果您想在验证器中执行此操作,请使用 custom validation rule:

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
    // Change column_b here to the name of your input
    'column_b' => function ($attribute, $value, $fail) use ($request) {
        $columnB = $value;
        // Change column_a here to the name of your input
        $columnA = $request->input('column_a');

        $records = DB::table('YOUR_TABLE')
            ->select('*')
            // Change column_a here to the name of column A in your database
            ->where('column_a', $columnA)
            // Change column_b here to the name of column B in your database
            ->where('column_b', $columnB)
            ->count();

        if($records > 0) {
            $fail("not allowed because value $columnB in Column B has already been set for value $columnA in column A");
        }
    },
]);