PHP 测试 JSON 包含 SQLite

标签 php mysql json laravel sqlite

我的 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/

相关文章:

php - 强制将记录插入多个表

php - 履带式+喷口 : Accessing to form

mysql - 查询对重复字段求和

json - ASP.NET Web Api 和部分响应

json - Spark 数据帧写入 JSON 显示 NULL 输出

php - 我正在尝试使用当前类制作 CSS 和 Javascript 菜单

php - 使用 PHP 将 Curl 检索到的 HTML 字符串转换为 JSON,使用 AJAX 服务

mysql 使用 set FIELD 和 case 导致排序错误

php - 我的 MySQLi 不只更新插入吗?我的脚本出了什么问题?

android - Gson toJson 将 "\n"添加到我的属性(property)的末尾