php - magento中的concat sql查询

标签 php mysql database magento

我是 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/

相关文章:

php - 内部动态 JavaScript

php - 从 .htaccess mod_rewrite 规则中排除子域?

mysql - 无法找到包 '6.9.5.0' 的版本 'MySql.Data.Entity.EF6'

php - 将基本表单发送到数据库

sql - 为什么 SELECT * 被认为是有害的?

c# - 将 MySql 数据库导出到文件中

PHP 写一个大文件 - 缓存 RAM

javascript - 拖放输入文件

php - MySQL查询每次执行时返回不同数量的记录

sql - 如何减少选择查询的执行时间