Silverstripe Version: 4.1
Goal is to get the records and iterate in the view to display them.
Raw SQL:
SELECT Products.*
FROM Products
INNER JOIN Products_Filters ON Products_Filters.ProductsID = Products.ID
WHERE Products.ProductListPagesID = 6 AND (
(Products_Filters.FilterID IN (1,13)) OR
(Products_Filters.FilterID IN(5, 7))
)
GROUP BY Products.ID
HAVING COUNT(Products.ID) = 2
ORDER BY Products.Title ASC
I’m struggling to get the WHERE how I need it with a mix of AND/OR. Need to AND the first part, and OR the rest which is a variable amount.
I’ve tried:
# $where[] = '(Products_Filters.FilterID IN ('.implode(',', $ids).'))';
$sql = new SQLSelect();
$sql->setSelect('Products.*');
$sql->setFrom('Products');
$sql->addInnerJoin('Products_Filters','"Products_Filters"."ProductsID" = "Products"."ID"');
$sql->addWhere(['Products.ProductListPagesID' => $this->ID]);
$sql->useDisjunction();
$sql->addWhere($where);
$sql->setGroupBy('Products.ID');
$sql->setHaving('COUNT(Products.ID) = '.count($where));
$sql->setOrderBy('Products.Title');
Added $sql->useDisjunction() in there for the OR but it does it on everything.
Resulting query:
SELECT Products.*
FROM Products
INNER JOIN "Products_Filters" ON "Products_Filters"."ProductsID" = "Products"."ID"
WHERE (Products.ProductListPagesID = ?) OR (
(Products_Filters.FilterID IN (1,3))) OR
((Products_Filters.FilterID IN (4))
)
GROUP BY Products.ID
HAVING (COUNT(Products.ID) = 2)
ORDER BY Products.Title ASC
So that query doesn’t get the WHERE part as I need.
It also generates an error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '“Products_Filters” ON “Products_Filters”.“ProductsID” = “Products”.“ID”
WHERE (’ at line 3
I changed the ? for 6 when running it…
If I remove the quotes around the JOIN fields from the generated SQL it doesn’t error. I quoted them like that from the docs (https://docs.silverstripe.org/en/3/developer_guides/model/sql_query/#usage)
If I remove them from the $sql->addInnerJoin(‘Product_Filters’, ‘Product_Filters.ProductsID = Products.ID’) the resulting query errors:
SELECT Products.*
FROM Products
INNER JOIN "Products_Filters" ON Products_Filters.ProductsID = Products.ID
WHERE (Products.ProductListPagesID = ?)
OR ((Products_Filters.FilterID IN (1,3)))
OR ((Products_Filters.FilterID IN (4,5)))
GROUP BY Products.ID
HAVING (COUNT(Products.ID) = 2)
ORDER BY Products.Title ASC
As the JOIN table is still quoted. Error is the same:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '“Products_Filters” ON Products_Filters.ProductsID = Products.ID
WHERE (Products’ at line 3
How can I get this query running correctly without errors?