Laravel: retrieve count of value in JSON array

Viewed 1283

Iv currently taken over a project where the developer has stored has many relationships in json array columns in certain tables.

product table

----------------------------
id | product | colour
----------------------------
 1   iPhone    ["8","4","1"]
 2   iPad      ["8","1"]
 3   Macbook   ["8"]

This is an example of the relationships stored between a product and product colours available.

I need to be able to get the count of products, related to a certian colour. So in this example... colour: 8 would return 3 products

I am use to Eloquent relationships utilising $product->colours() but unfortunately in this instance i can't do that, and i am unable to change the current db structure.

How would i be able to get the amount of products per certain colour using eloquent where or whereIn clauses?

What i have tried so far...

$count = $products->where('colour', '[$colour->id]')->count();
----
$count = $products->whereIn('colour', $colour->id)->count();

Any help would be greatly appreciated. Thanks in advance.

1 Answers

This is ugly, but I guess it works:

\App\Product::where('colour','like','%"' .$colour->id '"%')->distinct()->count()
Related