我的 Web 应用程序使用 Laravel 和 MySQL,但对于我的测试,我在内存中使用 SQLite。
这是我在 Controller 中使用的代码:
$opportunities = DB::table('opportunities')
->whereRaw('JSON_CONTAINS(businesses, \'"' . $business . '"\')')
->get();
测试时会抛出异常,因为 SQLite 没有 JSON_CONTAINS 函数。我怎样才能解决这个问题,以便我的测试通过并且我不必对结构进行任何重大更改? SQLite 是否有针对此或类似内容的函数?
谢谢
最佳答案
您可以在测试期间使用 sqlite_create_function
模拟 JSON_CONTAINS
例如
function json_contains($json, $val) {
$array = json_decode($json, true);
// trim double quotes from around the value to match MySQL behaviour
$val = trim($val, '"');
// this will work for a single dimension JSON value, if more dimensions
// something more sophisticated will be required
// that is left as an exercise for the reader
return in_array($val, $array);
}
sqlite_create_function(<your db handle>, 'JSON_CONTAINS', 'json_contains');
您可能还想模拟 JSON_CONTAINS
的可选第三个参数,例如
function json_contains($json, $val, $path = null) {
$array = json_decode($json, true);
// trim double quotes from around the value to match MySQL behaviour
$val = trim($val, '"');
// this will work for a single dimension JSON value, if more dimensions
// something more sophisticated will be required
// that is left as an exercise for the reader
if ($path)
return $array[$path] == $val;
else
return in_array($val, $array);
}
关于PHP 测试 JSON 包含 SQLite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50535778/