I would advise you to improve that SQL query before converting it. Don't know about you, but 500ms for a query is not acceptable.
Query Builder with WhereIn ANDs
I'm wondering if anyone has any suggestions on how I might convert the following example SQL to Query Builder:
SELECT DISTINCT p.product_id
FROM products AS p
WHERE p.product_id IN
(
SELECT product_id
FROM product_components
WHERE product_id = p.product_id
AND code = 'RSTCW')
AND
(
SELECT product_id
FROM product_components
WHERE product_id = p.product_id
AND code = 'RSTLAD')
AND
(
SELECT product_id
FROM product_components
WHERE product_id = p.product_id
AND code = 'RSTRLAD')
AND
(
SELECT product_id
FROM product_components
WHERE product_id = p.product_id
AND code = 'RSTPSW')
My problem is that I've been unable to come up with a Query Builder version of this. The closest I've been able to get is to use chained $query->whereIn calls, but that results in unacceptably slow execution times if there are more than 3 or 4 subselects. Whereas, with the SQL above, total execution time never exceeds 500ms, regardless of the number of subselects.
So the question comes down to this: does anyone know how I might output this exact SQL using Query Builder? Thanks for any pointers you might have!
As @bugsysha suspected, this was a case of a me misunderstanding my SQL followed by poor simplification by me of that SQL. The problem and solution I found are so unrelated to the question I posted that I'm not going to bother to post anything here. I will say that whereRaw() came in very handy. I appreciate the thoughtful responses from people here. Next time I have a question I will try to have it better in hand before I post!
Please or to participate in this conversation.