简体   繁体   中英

JSON Search in laravel eloquent

I am storing destinations field as json type in mysql

example column value ["Goa", "Moonar", "Kochi"]

I would like to get all rows that matches goa as destinations

However this row query returns the desired result

SELECT * FROM `packages` 
WHERE JSON_CONTAINS(destinations, '["Goa"]');

But what is the eloquent equivalent of the above query??

Laravel version 5.3

Modelname : Search

Probably forced to use a partially raw query like:

use DB; (top of file definition)

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

And if you have a model:

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

assuming your query above works in SQL.

In Laravel 5.6 and higher you can use whereJsonContains method:

Package::whereJsonContains('destinations',["Goa"])->get();

But not all DB support it: https://laravel.com/docs/5.6/queries#json-where-clauses

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM