I am working on a module to remove images of all deleted products, which is not the standard M2 behavior. My initial query to found images path still used by products was :
$connection = $this->connection->getConnection();
$select = "SELECT {$connection->getTableName('catalog_product_entity_media_gallery')}.value"
." FROM {$connection->getTableName('catalog_product_entity_media_gallery_value_to_entity')}"
." , {$connection->getTableName('catalog_product_entity_media_gallery')}"
." WHERE {$connection->getTableName('catalog_product_entity_media_gallery_value_to_entity')}"
." .value_id = {$connection->getTableName('catalog_product_entity_media_gallery')}.value_id"
." UNION"
." SELECT {$connection->getTableName('core_config_data')}.value"
." FROM {$connection->getTableName('core_config_data')}"
." WHERE {$connection->getTableName('core_config_data')}.path"
." LIKE '%placeholder%'";
return $connection->fetchCol($select);
I use PHP_CodeSniffer from magento-coding-standard and result is a warning for a potential raw SQL. To fix this, I finally use this query :
$connection = $this->connection->getConnection();
$placeholders = $connection->select()
->from('core_config_data')
->where('core_config_data.path LIKE "%placeholder%"')
->reset(Zend_Db_Select::COLUMNS)
->columns('value');
$sqlImages = $connection->select()
->from(['gallery' => 'catalog_product_entity_media_gallery'])
->join(
['to_entity' => 'catalog_product_entity_media_gallery_value_to_entity'],
'gallery.value_id = to_entity.value_id'
)
->reset(Zend_Db_Select::COLUMNS)
->columns('value');
$select = $connection->select()->union([$sqlImages, $placeholders], Select::SQL_UNION_ALL);
return $connection->fetchCol($select);
Same result but I wonder if it is not possible to compact it in a single query like the first one?
(all the examples i find in the M2 core are always combinations of several queries)