JSON Search in laravel eloquent

2019-04-07 22:20发布

问题:

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

回答1:

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.