首页 > 解决方案 > 如何在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。

请帮忙。

标签: sqljsonlaravel

解决方案


$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));

推荐阅读