Hope anybody can help me, I need to search for items that have category id = x in the database
Example table items id,cats,name etc... cats = \'1,19\' or maybe just \'1
It's quite hard to understand what you want to achieve but I'll try. First of all as @particus mentioned the best way is to create pivot table when you don't need to worry about such things.
But the solution if you have list of ids in a columns separated by coma is not storing values like
1,2,3
but always adding ,
at the beginning and at the end, so it should be in this case:
,1,2,3,
This way, if you have in your table ,19,2,3,
and you want to search for value 9
, you should use look for ,9,
string, for example:
$id = 9;
$items = Items::where('column', LIKE '%,'.$id.',%')->get();
Now for above string no record will be found, but if you have ,9,2,3,
or just ,9,
the desired record will be found.
Assuming you're using MySQL, you can use the FIND_IN_SET function.
$items = Items::whereRaw("FIND_IN_SET(".$cat->id.", cats)")->orderBy('updated_at', 'DESC')->get();
Please note, this will not use any indexes defined on the cats column. Storing array like data in a field is usually a big red flag. You would benefit by normalizing this out now, rather than trying to work around the current design.