tl;博士
public function rules() {
return [
'data.room_id' => [
Rule::exists('rooms', 'id')->where(function ($query) {
$query->where('is_open', 1);
})
]
];
}
使用exists 进行验证
有documentation on the exists 规则,但它非常简洁。让我们看看文档中的命令实际上是什么意思。这条规则的要点是它可以根据某些标准验证数据库中表中是否存在字段。例如,当您保存预订时,您可以验证您预订的房间是否存在于数据库中。
基本用法
'size' => 'exists:rooms'
这将检查rooms 表是否有一个条目,其中size 列包含的值是正在验证的值(在这种情况下,键size 的对应值是large)。这会产生以下 SQL 查询:
select count(*) as aggregate from `rooms` where `size` = "large";
指定自定义列名
在上一节中,已验证列的名称来自已验证属性的键 ('size')。您可能希望提供不同的列名,因为您正在验证与数据键名称不同的列(例如,“大小”存储在“类别”列中)另一种情况是您的 rooms 表的主键只是id 而不是 room_id 就像在验证数据中一样。在您的情况下,验证数据的键是 data.room_id,但您想检查 rooms 的 id 列。您可以指定以逗号分隔的列名称:
'data.room_id' => 'exists:rooms,id'
这将检查rooms 表是否有一个条目,其中id 列包含正在验证的值,从而导致以下SQL 查询:
select count(*) as aggregate from `rooms` where `id` = 4;
使用额外的子句指定自定义列名称
如果您需要进一步过滤结果,您可以使用Illuminate\Validation\Rule 类。您传递表和列名(第二个是可选的,就像在基本用法部分中一样)并在匿名函数中将额外的子句添加到查询中。您可以使用请求中的每个输入数据,只需使用$this->input('propertyName') 或$this->all() 检索它,然后手动处理它:
'data.room_id' => [
Rule::exists('rooms', 'id')->where(function ($query) {
$query
->where('is_open', 1);
->where('size', $this->input('data.size'));
})
]
生成的 SQL 查询是这样的:
select count(*) as aggregate from `rooms` where `id` = 4 and (`is_open` = 1 and `size` = large);
$query 变量中的可用子句是 where、whereNot、whereNull、whereNotNull、whereIn 和 whereNotIn。查看Illuminate/Validation/Rules/Exists class docs。