sql - 如何在laravel的json数组列中找到字符串搜索的位置
问题描述
我有一个查询,它从 json 数组列返回关于我正在搜索的字符串是否存在的布尔值
该列是这样的 ------ ["a","b","c"] 并且查询如下
DB::table('product_lines as l')->where('l.id',$position->product_line_id)
->whereRaw('json_contains(l.types, \'["b"]\')')->first()->count();
但我想得到找到字符串的位置......让我们说它应该返回1。
请帮忙。
解决方案
$pl = DB::table('product_lines as pl')
->select(DB::raw('JSON_SEARCH(pl.types, "one", "b") as
idx'))
->where('id', $position->product_line_id)
->whereRaw('JSON_CONTAINS(pl.types, \'"b"\', \'$\')')
->first();
dd($pl->idx);
它会给你作为"$[1]"
""
输出字符串的一部分的输出。所以你需要得到之间的数字[]
才能得到数组中项目的索引。
或者
$pl = DB::table('product_lines as pl')
->where('id', $position->product_line_id)
->whereRaw('JSON_CONTAINS(pl.types, \'"b"\', \'$\')')
->first();
$arr = json_decode($pl->types);
dd(array_search("b", $arr));
推荐阅读
- c++ - build2:编译器不支持模块
- ruby-on-rails - ruby on rails best_in_place nomethoderror
- r - 为什么悬停文本不适用于 ggplotly、geom_histogram 和 facet_grid?
- ios - 由 UIAlert 按钮选择启动的导航的 SWReveal 问题
- docker - Minikube 操作超时
- r - 改变数据框的结构
- llvm - 使用 Bazel 构建 LLVM
- bash - 在终端中将值转换为多线条形图
- apache - Apache服务器重启错误
- javascript - 是否应该为生产构建删除 NGXS NgxsLoggerPluginModule?