How to found item in sql Array laravel

44 views Asked by At

I am trying to find an item by id, but my column is a comma separated string(primaryCategory in below screenshot). I want to get this field in my result when query by any string (i.e. by 50,20,41 etc).

I know there could be options like whereIn, whereHas etc. but not able to find correct syntax. Please help me with this.

enter image description here

1

There are 1 answers

1
V-K On

Using comma separated string is bad practice for that task, better to create a new table. But for your structure this way with func FIND_IN_SET is suitable: https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_find-in-set

$categories = [1,2,3];

$queryParts = [];
foreach($categories as $category) {
    $queryParts[] = 'FIND_IN_SET("' . $category . '", `primaryCategory`)';
}

$query = implode(' OR ', $queryParts);

$list = Model::whereRaw($query)->get();

UPD Righ solution

Use *ToMany relation:

https://laravel.com/docs/8.x/eloquent-relationships#one-to-many https://laravel.com/docs/8.x/eloquent-relationships#many-to-many

You have to create a new table: model_categories and put there model_id and category_id. Every model can have several categories and vise versa, and then you can use the standard laravel whereHas function to find models with special categories.