JSON搜索laravel雄辩

iam*_*man 8 php mysql laravel-5

我将destinations字段存储为json类型mysql

示例列值 ["Goa", "Moonar", "Kochi"]

我想获得匹配的所有行goa作为目的地

但是,此行查询返回所需的结果

SELECT * FROM `packages` 
WHERE JSON_CONTAINS(destinations, '["Goa"]');
Run Code Online (Sandbox Code Playgroud)

但是上述查询的雄辩等价是什么?

Laravel版本5.3

型号名称 :Search

Ant*_*hev 15

在 Laravel 5.6 及更高版本中,您可以使用 whereJsonContains 方法:

Package::whereJsonContains('destinations',["Goa"])->get();
Run Code Online (Sandbox Code Playgroud)

但并非所有数据库都支持它:https : //laravel.com/docs/5.6/queries#json-where-clauses


Jon*_*han 12

可能被迫使用部分原始查询,如:

use DB; (文件定义的顶部)

DB::table('packages')->whereRaw('json_contains(destinations, \'["Goa"]\')')->get();

如果你有一个型号:

Package::whereRaw('json_contains(destinations, \'["' . $keyword . '"]\')')->get();

假设您的上述查询在SQL中有效.