我是 magento 的新手。我正在编写如下代码:
$products = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*')
->addAttributeToSort("entity_id", "DESC")
->addAttributeToSelect(array('name', 'price', 'small_image'))
->setVisibility ( Mage::getSingleton( 'catalog/product_visibility')->getVisibleInSiteIds())
->setOrder($this->get_order(), $this->get_order_dir());
然后,当使用条件时,通过使用 $products 的值,我编写的代码如下:
if($size != ''){
$products->getSelect()
->joinLeft(array('cat_product' => 'catalog_category_product'), 'cat_product.product_id=e.entity_id')
->joinLeft(array("at_int" => 'catalog_product_entity_int'), 'cat_product.product_id=at_int.entity_id')
->joinLeft(array('cpf'=>'catalog_product_flat_1'),'cpf.entity_id=e.entity_id',array('shhirt_size'))
->where('at_int.value=30 AND cpf.shhirt_size='.$size.' AND at_int.attribute_id=(SELECT `attribute_id` FROM `eav_attribute` WHERE `attribute_code`="product_attrb_type_name") ')
;
}else if($size == ''){
$products->getSelect()
->joinLeft(array('cat_product' => 'catalog_category_product'), 'cat_product.product_id=e.entity_id')
->joinLeft(array("at_int" => 'catalog_product_entity_int'), 'cat_product.product_id=at_int.entity_id')
->where('at_int.value=30 AND at_int.attribute_id=(SELECT `attribute_id` FROM `eav_attribute` WHERE `attribute_code`="product_attrb_type_name") ' )
;
}
工作正常。但这里代码被重写了。上面的代码如何写成这样,if部分和else部分只有where子句。
请帮助我。 提前致谢。
最佳答案
我使用了 Haim Evgi 的解决方案并稍微修正了它
$subSelect = clone $products->getSelect(); $subSelect->reset() ->from($products->getTable('eav_attribute'), array('attribute_id')) ->where('`attribute_code`="product_attrb_type_name"'); $q = $products->getSelect() ->joinLeft(array('cat_product' => 'catalog_category_product'), 'cat_product.product_id=e.entity_id') ->joinLeft(array("at_int" => 'catalog_product_entity_int'), 'cat_product.product_id=at_int.entity_id') ->where('at_int.value=30') ->where('at_int.attribute_id=?', new Zend_Db_Expr(sprintf('(%s)', $subSelect))); if($size != ''){ $q->joinLeft(array('cpf'=>'catalog_product_flat_1'), 'cpf.entity_id=e.entity_id', array('shhirt_size')) ->where('cpf.shhirt_size=?', $size); }
关于php - magento中的concat sql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24630529/