Skip to content
Advertisement

MySQL (Laravel Eloquent) – Get record when two columns have two or more values at the same time

I have this database that I got from this post that manages products and its variants:

The problem is, that I don’t know how would I get the SKU at the moment that a user selects the options of the product he wants:

Let’s suppose that the user selects the product with ID 1 and the options size-small and color-black, how am I able to get the sku_id (in this case I would want value 2 from sku_id) in order to get the price that’s inside the PRODUCT_SKUS table.

I cannot do something like this for obvious reasons:

NOTE that it seems that I would need to append the same number of conditions (or whatever I need) as the number of options that are available from a product, in this case there are just 2 rows because the product has 2 options (size and color), but the product may have “n” options.

I would appreciate if someone could guide me for this query and if it’s possible doing it with Laravel Eloquent instead of using RAW query.

The models I have created are the following:

“Product” Model:

“Options” Model:

“OptionValues” Model:

“Product_SKUS” model:

“SKU_VALUES” model:

Advertisement

Answer

Here is a solution using pure SQL.

This is your attempt using a raw query:

This doesn’t work because you need to search across rows sharing the same sku_id rather than on each row. This suggest aggregation:

You can easily extend the query for more options by adding more combinations in the where clause predicate and incrementing the target count in the having clause accordingly. For example, this filters on 4 criterias:

It is also possible to filter by option names and values by adding more joins in the subquery:

Now, say you want to get the corresponding product name and price: you can join the above query with the relevant tables.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement