这是我研究了一段时间后的一种方法。我想做一个 Laravel API 端点来检查一个字段是否“正在使用”,所以重要的信息是:1)哪个 DB 表? 2)什么数据库列? 3) 该列中是否有与搜索词匹配的值?
知道了这一点,我们就可以构造我们的关联数组了:
$SEARCHABLE_TABLE_COLUMNS = [
'users' => [ 'email' ],
];
然后,我们可以设置我们要检查的值:
$table = 'users';
$column = 'email';
$value = 'alice@bob.com';
然后,我们可以使用array_key_exists() 和in_array() 来执行一两步组合,然后根据truthy 条件进行操作:
// step 1: check if 'users' exists as a key in `$SEARCHABLE_TABLE_COLUMNS`
if (array_key_exists($table, $SEARCHABLE_TABLE_COLUMNS)) {
// step 2: check if 'email' is in the array: $SEARCHABLE_TABLE_COLUMNS[$table]
if (in_array($column, $SEARCHABLE_TABLE_COLUMNS[$table])) {
// if table and column are allowed, return Boolean if value already exists
// this will either return the first matching record or null
$exists = DB::table($table)->where($column, '=', $value)->first();
if ($exists) return response()->json([ 'in_use' => true ], 200);
return response()->json([ 'in_use' => false ], 200);
}
// if $column isn't in $SEARCHABLE_TABLE_COLUMNS[$table],
// then we need to tell the user we can't proceed with their request
return response()->json([ 'error' => 'Illegal column name: '.$column ], 400);
}
// if $table isn't a key in $SEARCHABLE_TABLE_COLUMNS,
// then we need to tell the user we can't proceed with their request
return response()->json([ 'error' => 'Illegal table name: '.$table ], 400);
对于 Laravel 特定的 PHP 代码,我深表歉意,但我会留下它,因为我认为您可以将其视为伪代码。 重要的部分是两个同步执行的if语句。
array_key_exists() 和 in_array() 是 PHP 函数。
来源:
我上面展示的算法的好处是,您可以创建一个 REST 端点,例如 GET /in-use/{table}/{column}/{value}(其中 table、column 和 value 是变量)。
你可以:
$SEARCHABLE_TABLE_COLUMNS = [
'accounts' => [ 'account_name', 'phone', 'business_email' ],
'users' => [ 'email' ],
];
然后您可以发出 GET 请求,例如:
GET /in-use/accounts/account_name/Bob's Drywall(你可能需要对最后一部分进行uri编码,但通常不需要)
GET /in-use/accounts/phone/888-555-1337
GET /in-use/users/email/alice@bob.com
还要注意没有人能做到:
GET /in-use/users/password/dogmeat1337 因为password 未列在user 的允许列列表中。
祝你旅途愉快。