我使用了这个查询:
$brands = TblBrand::find(array("id In (Select p.brand_id From EShop\\Models\\TblProduct as p Where p.id In (Select cp.product_id From EShop\\Models\\TblProductCategory as cp Where cp.group_id_1='$id'))", "order" => "title_fa asc"));
if($brands != null and count($brands) > 0)
{
foreach($brands as $brand)
{
$brandInProductCategory[$id][] = array
(
"id" => $brand->getId(),
"title_fa" => $brand->getTitleFa(),
"title_en" => $brand->getTitleEn()
);
}
}
TblBrand => 110条记录
TblProduct => 2000条记录
TblProductCategory => 2500条记录
当我使用此代码时,我的网站显示和加载页面很长时间... 但当我删除此代码时,我的网站显示。
如何解决这个问题?
答案 0 :(得分:1)
问题是您的查询。您正在以嵌套格式使用IN
语句,并且总是比其他任何语句都慢。 MySQL需要首先评估IN语句中的内容,返回该语句,然后再对下一级记录进行重复操作。
尝试简化查询。像这样:
SELECT *
FROM Brands
INNER JOIN Products ON Brand.id = Products.brand_id
INNER JOIN ProductCategory ON ProductCategory.product_id = Products.id
WHERE ProductCategory.group_id_1 = $id
要实现上述目标,您可以使用查询生成器并以此方式获得结果
https://docs.phalconphp.com/en/latest/api/Phalcon_Mvc_Model_Query_Builder.html
或者如果您在品牌,产品和产品类别之间的模型中建立了关系,则可以使用它。
https://docs.phalconphp.com/en/latest/reference/model-relationships.html
答案 1 :(得分:0)
示例:
$Brands = Brands::query()
->innerJoin("Products", "Products.brand_id = Brand.id")
->innerJoin("ProductCategory", "ProductCategory.product_id = Products.id")
->where("ProductCategory.group_id_1 = :group_id:")
->bind(["group_id" => $id])
->cache(["key" => __METHOD__.$id] // if defined modelCache as DI service
->execute();
$brandInProductCategory[$id] = [];
foreach($Brands AS $Brand) {
array_push($brandInProductCategory[$id], [
"id" => $Brand->getId(),
"title_fa" => $Brand->getTitleFa(),
"title_en" => $Brand->getTitleEn()
]);
}