I'm using Laravel Eloquent and debuging why this query is taking so long:
select count(*) as aggregate
from `custom_products`
where `hidden` = '0'
and (`company_id` = '1')
and exists (
select * from `categories`
inner join `categorizables` on `categories`.`id` = `categorizables`.`category_id`
where `custom_products`.`id` = `categorizables`.`categorizable_id`
and `categorizables`.`categorizable_type` = 'App\Models\CustomProduct'
and `categories`.`deleted_at` is null)
and exists (
select * from `images`
where `custom_products`.`id` = `images`.`imageable_id`
and `images`.`imageable_type` = 'App\Models\CustomProduct'
and `images`.`deleted_at` is null)
and `custom_products`.`deleted_at` is null
Sometimes it runs very slow: it tooks 17.46s to run as you see in this image from debugbar:
Anyone knows why?
images
. imageable_id
is that the PRIMARY KEY
? Provide SHOW CREATE TABLE
for each table.
What indexes are there on custom_products
? It needs
INDEX(company_id, hidden, deleted_at)
On a different topic, I think you have a bug in 'App\\Models\\CustomProduct'
-- backslash is the escape character, not a directory separator. Probably you need 'App\\\\Models\\\\CustomProduct'
Try to add these indexes to optimize the query:
ALTER TABLE `categories` ADD INDEX `categories_idx_at_id` (`deleted_at`,`id`);
ALTER TABLE `categorizables` ADD INDEX `categorizables_idx_type_id_id` (`categorizable_type`,`category_id`,`categorizable_id`);
ALTER TABLE `custom_products` ADD INDEX `custom_products_idx_hidden_id_at` (`hidden`,`company_id`,`deleted_at`);
ALTER TABLE `custom_products` ADD INDEX `custom_products_idx_id` (`id`);
ALTER TABLE `images` ADD INDEX `images_idx_type_at_id` (`imageable_type`,`deleted_at`,`imageable_id`);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.