Выбор элементов магазина по доп. свойствам

#
Выбор элементов магазина по доп. свойствам
Вопрос #1
Что не так делаю? Я взял пример с информационной системой и переделал на магазин.


   $Shop_Controller_Show = new Shop_Controller_Show(
                     Core_Entity::factory('Shop', 2)
            );
            $Shop_Controller_Show
                ->xsl(
                   Core_Entity::factory('Xsl')->getByName('СпецПредложения')
                )
                ->groupsMode('none')
                ->group(false);
                    
            $Shop_Controller_Show->shopItems()
                    ->queryBuilder()
                    ->leftJoin('shop_item_properties', 'shop_items.shop_id', '=', 'shop_item_properties.shop_id')
                    ->leftJoin('property_value_ints', 'shop_items.id', '=', 'property_value_ints.entity_id',
                                array(
                                    array('AND' => array('shop_item_properties.property_id', '=',
                                    Core_QueryBuilder::expression('`property_value_ints`.`property_id`')))
                                )
                     )
                     // Идентификатор дополнительного свойства
                     ->where('shop_item_properties.property_id', '=', 89)
                     // Значание дополнительного свойства
                     ->where('property_value_ints.value', '=', '1')
                ->limit(999);
            $Shop_Controller_Show->show();
                  
            $sLastQuery = Core_DataBase::instance()->getLastQuery();
            echo htmlspecialchars($sLastQuery);

//вывод  SELECT COUNT(*) AS `count` FROM `shop_items` WHERE `shop_items`.`shop_id` = '2' AND `shop_items`.`shop_group_id` = 0 AND `shop_items`.`deleted` = 0


Вопрос №2

У меня группы сортируется не по имени. Мне надо взять все группы и сделать сортировку по имени. Но в других вызовах мне нужна выборка по полю сортировки, и настройка стоит по полю сортировки в административной части. Что не так делаю?


            $oShop = Core_Entity::factory('Shop', 2);

            $oShop ->Shop_Groups ->queryBuilder()
                    ->clearOrderBy()
                    ->orderBy('shop_groups.name', 'ASC');
d-sant.com
Модератор
#
Re: Выбор элементов магазина по доп. свойствам
t0xas, по первому вопросу что именно не работает? Все выбирается или наоборот ничего? Проблема не обозначена.
2. это только неполный фрагмент кода, что Вы им хотели добавиться? Где "обвязка"?
#
Re: Выбор элементов магазина по доп. свойствам
1. ничего не выбирается.

<shop id="2">
   <shop_dir_id>0</shop_dir_id>
   <shop_company_id>1</shop_company_id>
   <site_id>1</site_id>
   <name>Объявления</name>
   <description></description>
   <yandex_market_name></yandex_market_name>
   <image_small_max_width>473</image_small_max_width>
   <image_small_max_height>473</image_small_max_height>
   <image_large_max_width>800</image_large_max_width>
   <image_large_max_height>800</image_large_max_height>
   <structure_id>413</structure_id>
   <shop_country_id>175</shop_country_id>
   <shop_currency_id>1</shop_currency_id>
   <shop_order_status_id>0</shop_order_status_id>
   <shop_measure_id>9</shop_measure_id>
   <email>admin@localhost.ru</email>
   <items_on_page>15</items_on_page>
   <url_type>1</url_type>
   <send_order_email_admin>0</send_order_email_admin>
   <send_order_email_user>0</send_order_email_user>
   <items_sorting_field>0</items_sorting_field>
   <items_sorting_direction>1</items_sorting_direction>
   <groups_sorting_field>0</groups_sorting_field>
   <groups_sorting_direction>0</groups_sorting_direction>
   <user_id>19</user_id>
   <comment_active>1</comment_active>
   <watermark_file></watermark_file>
   <watermark_default_use_large_image>0</watermark_default_use_large_image>
   <watermark_default_use_small_image>0</watermark_default_use_small_image>
   <watermark_default_position_x></watermark_default_position_x>
   <watermark_default_position_y></watermark_default_position_y>
   <guid></guid>
   <format_date>%d.%m.%Y</format_date>
   <format_datetime>%d.%m.%Y %H:%M:%S</format_datetime>
   <typograph_default_items>0</typograph_default_items>
   <typograph_default_groups>0</typograph_default_groups>
   <apply_tags_automatically>1</apply_tags_automatically>
   <write_off_paid_items>0</write_off_paid_items>
   <apply_keywords_automatically>0</apply_keywords_automatically>
   <change_filename>1</change_filename>
   <attach_digital_items>1</attach_digital_items>
   <yandex_market_sales_notes_default></yandex_market_sales_notes_default>
   <siteuser_group_id>0</siteuser_group_id>
   <use_captcha>1</use_captcha>
   <group_image_small_max_width>100</group_image_small_max_width>
   <group_image_large_max_width>320</group_image_large_max_width>
   <group_image_small_max_height>100</group_image_small_max_height>
   <group_image_large_max_height>320</group_image_large_max_height>
   <preserve_aspect_ratio>1</preserve_aspect_ratio>
   <url>/announcements/</url>
   <captcha_id>27242</captcha_id>
   <items_count>0</items_count>
   <items_total_count>103</items_total_count>
   <subgroups_count>6</subgroups_count>
   <subgroups_total_count>1403</subgroups_total_count>
   <siteuser_id>0</siteuser_id>
   <group>0</group>
   <page>0</page>
   <limit>0</limit>
   <shop_currency id="1">
      <name>руб.</name>
      <code>RUB</code>
      <exchange_rate>1.000000</exchange_rate>
      <default>1</default>
      <sorting>10</sorting>
      <user_id>19</user_id>
   </shop_currency>
   <shop_measure id="9">
      <name>боб</name>
      <description>бобина</description>
      <user_id>19</user_id>
   </shop_measure>
   <shop_warehouse id="2">
      <shop_id>2</shop_id>
      <name>Основной</name>
      <sorting>0</sorting>
      <active>1</active>
      <default>0</default>
      <shop_country_id>0</shop_country_id>
      <shop_country_location_id>0</shop_country_location_id>
      <shop_country_location_city_id>0</shop_country_location_city_id>
      <shop_country_location_city_area_id>0</shop_country_location_city_area_id>
      <address></address>
      <user_id>0</user_id>
   </shop_warehouse>
</shop>


2.



$oShop = Core_Entity::factory('Shop', 2);

            $oShop ->Shop_Groups ->queryBuilder()
                    ->clearOrderBy()
                    ->orderBy('shop_groups.name', 'ASC');
            
$aShop_groups = $oShop->Shop_Groups->findAll();
            ?>
<select name="marka">
            <?foreach ($aShop_groups as $oShop_groups):?>
                    <option value="<?=$oShop_groups->id?>">
                          <?=$oShop_groups->name?>
                    </option>
            <?endforeach;?>
</select>
d-sant.com
Модератор
#
Re: Выбор элементов магазина по доп. свойствам
1. Обратитесь в поддержку, явной ошибки не вижу.
2. неправильно, Ваши условия никак не влияют на Shop_Groups, т.к. при каждом вызове ->Shop_Groups Вы получаете новый объект связи. Нужно так:
$oShop = Core_Entity::factory('Shop', 2);

$oShop_Groups = $oShop->Shop_Groups;
$oShop_Groups->queryBuilder()
   ->clearOrderBy()
   ->orderBy('shop_groups.name', 'ASC');
            
$aShop_groups = $oShop_Groups->findAll();

...
#
Re: Выбор элементов магазина по доп. свойствам
Благодарю!
d-sant.com
#
Re: Выбор элементов магазина по доп. свойствам
А тут такой вопрос возник,
надо выбирать товары из магазина по двум-трем-четырем-пяти и тд. свойствам, причем товар должен обладать всеми заданными свойствами, я тут полазил по форумы и ничего не нашёл, пробовал примеры, но увы не получается, пытался разобратся с кодом интрнет-магазина (ТДС), но тоже не получилось.

У меня код выглядит сейчас так. Я не понимаю всех тонкостей mysql, прошу направить на путь истинный.


    $Shop_Controller_Show = new Shop_Controller_Show(
                     Core_Entity::factory('Shop', 2)
            );
    
     $Shop_Controller_Show
                ->xsl(
                   Core_Entity::factory('Xsl')->getByName('СписокОбъявлений')
                )
                ->groupsMode('none')
                ->limit(50)
                    ->itemsProperties(TRUE)
                    ->group(false);
              
        $Shop_Controller_Show->shopItems()->queryBuilder()
            ->leftJoin('shop_item_properties', 'shop_items.shop_id', '=', 'shop_item_properties.shop_id')
            ->leftJoin('property_value_ints', 'shop_items.id', '=', 'property_value_ints.entity_id',
                  array(
                      array('AND' => array('shop_item_properties.property_id', '=',
                           Core_QueryBuilder::expression('`property_value_ints`.`property_id`')))
                         )
                  )
            ->leftJoin('property_value_files', 'shop_items.id', '=', 'property_value_files.entity_id',
                  array(
                      array('AND' => array('shop_item_properties.property_id', '=',
                           Core_QueryBuilder::expression('`property_value_files`.`property_id`')))
                         )
                  );
    
     $flag = false;
    
  
   $Shop_Controller_Show->shopItems()->queryBuilder()
            ->open();
            $ch = 0;
     if(isset($condishion) and $condishion > 0 ) {
        $Shop_Controller_Show->shopItems()->queryBuilder()
                // Идентификатор дополнительного свойства
            ->where('shop_item_properties.property_id', '=', 72)
                // Значание дополнительного свойства
            ->where('property_value_ints.value', '=', $condishion);
            $ch++;
       }
    
     if(isset($city) and $city > 0 ) {
      
        
        $Shop_Controller_Show->shopItems()->queryBuilder()
                // Идентификатор дополнительного свойства
            ->where('shop_item_properties.property_id', '=', 95)
                // Значание дополнительного свойства
            ->where('property_value_ints.value', '=', $city);
        $ch++;
     }
    
     if($photo) {
        $Shop_Controller_Show->shopItems()->queryBuilder()
            
                // Идентификатор дополнительного свойства
            ->where('shop_item_properties.property_id', '=', 84)
                // Значание дополнительного свойства
            ->where('property_value_files.file', '!=', '');
        $ch++;
     }
      
      
     if(isset($year_start) and $year_start > 0 and isset($year_end) and $year_end > 0 ) {
        
        $Shop_Controller_Show->shopItems()->queryBuilder()
                // Идентификатор дополнительного свойства
            ->where('shop_item_properties.property_id', '=', 66)
                // Значание дополнительного свойства
            ->where('property_value_ints.value', '>=', $year_start)
            ->where('property_value_ints.value', '<=', $year_end);
            $ch++;
       }
        $Shop_Controller_Show->shopItems()->queryBuilder()->close();
      
        if(isset($price) and $price > 0 ) {  
         // Получаем список валют магазина
         $aShop_Currencies = Core_Entity::factory('Shop_Currency')->findAll();

         $query_currency_switch = 'price';
         
            $oShop = $Shop_Controller_Show->getEntity();
                        
            foreach ($aShop_Currencies as $oShop_Currency)
         {
            // Получаем коэффициент пересчета для каждой валюты
            $currency_coefficient = Shop_Controller::instance()->getCurrencyCoefficientInShopCurrency(
               $oShop_Currency, $oShop->Shop_Currency
            );

            $query_currency_switch = "IF (`shop_items`.`shop_currency_id` = '{$oShop_Currency->id}', IF (shop_discounts.percent, price * (100 - shop_discounts.percent) * {$currency_coefficient} / 100, shop_items.price * {$currency_coefficient}), {$query_currency_switch})";
         }

         $current_date = date('Y-m-d H:i:s');
         $Shop_Controller_Show->shopItems()
            ->queryBuilder()
            ->select(array(Core_QueryBuilder::expression($query_currency_switch), 'absolute_price'))
            ->leftJoin('shop_item_discounts', 'shop_items.id', '=', 'shop_item_discounts.id')
            ->leftJoin('shop_discounts', 'shop_item_discounts.id', '=', 'shop_discounts.id', array(
               array('AND (' => array('shop_discounts.end_datetime', '>=', $current_date)),
               array('OR' => array('shop_discounts.end_datetime', '=', '0000-00-00 00:00:00')),
               array('AND' => array('shop_discounts.start_datetime', '<=', $current_date)),
               array(')' => NULL)
            ));

            
            
            $Shop_Controller_Show->shopItems()->queryBuilder()->having('absolute_price', '<=', $price);
            $Shop_Controller_Show->addEntity(
               Core::factory('Core_Xml_Entity')
                  ->name('price_to')->value($price)
            );

         $Shop_Controller_Show->shopItems()->queryBuilder()
            ->clearOrderBy()
            ->orderBy('absolute_price', 'ASC');
      }
  
  
  
   $Shop_Controller_Show->shopItems()->queryBuilder()->groupBy('shop_items.id')->having('COUNT(shop_item_properties.id)', '=', $ch);
  
   $Shop_Controller_Show->shopItems()->queryBuilder()->where('shop_items.shop_group_id', 'IN', $neededGroups);                    
   $Shop_Controller_Show->show();

d-sant.com
Модератор
#
Re: Выбор элементов магазина по доп. свойствам
t0xas, так в чем проблема? Ничего не ищет или наоборот ищет больше, чем нужно?
#
Re: Выбор элементов магазина по доп. свойствам
Ничего не ищет.
d-sant.com
Модератор
#
Re: Выбор элементов магазина по доп. свойствам
Забыли setOr между блоками условий. У Вас не может свойство быть равно 1, 2, 3 и т.д. одновременно. Разделяйте блоки условий по значениям св-ва через setOr()
#
Re: Выбор элементов магазина по доп. свойствам
А так лабуда какая-то ищется, можете попробовать тут. http://dev2.aszsoft.com/search-ads/engineering/
С таким запросом выдаются элементы магазина по нескольку раз, потому что находятся по каждому свойству. Например если удовлетворяет трем заданным свойствам. то выводятся три раза. Что делать? Как быть? я не очень силен в скуль.

$Shop_Controller_Show = new Shop_Controller_Show(
                     Core_Entity::factory('Shop', 2)
            );
    
     $Shop_Controller_Show
                ->xsl(
                   Core_Entity::factory('Xsl')->getByName('СписокОбъявлений')
                )
                ->groupsMode('none')
                ->limit(50)
                    ->itemsProperties(TRUE)
                    ->group(false);
              
        $Shop_Controller_Show->shopItems()->queryBuilder()
            ->leftJoin('shop_item_properties', 'shop_items.shop_id', '=', 'shop_item_properties.shop_id')
            ->leftJoin('property_value_ints', 'shop_items.id', '=', 'property_value_ints.entity_id',
                  array(
                      array('AND' => array('shop_item_properties.property_id', '=',
                           Core_QueryBuilder::expression('`property_value_ints`.`property_id`')))
                         )
                  )
            ->leftJoin('property_value_files', 'shop_items.id', '=', 'property_value_files.entity_id',
                  array(
                      array('AND' => array('shop_item_properties.property_id', '=',
                           Core_QueryBuilder::expression('`property_value_files`.`property_id`')))
                         )
                  );
    
     $flag = false;
    
  
   $Shop_Controller_Show->shopItems()->queryBuilder()
            ->open();
            $ch = 0;
     if(isset($condishion) and $condishion > 0 ) {
        $flag = true;
        $Shop_Controller_Show->shopItems()->queryBuilder()
                // Идентификатор дополнительного свойства
                
            ->where('shop_item_properties.property_id', '=', 72)
                // Значание дополнительного свойства
            ->where('property_value_ints.value', '=', $condishion);
            $ch++;
       }
    
     if(isset($city) and $city > 0 ) {
        
        if($flag)
             $Shop_Controller_Show->shopItems()->queryBuilder()->setOr();
        else
            $flag = true;
            
        $Shop_Controller_Show->shopItems()->queryBuilder()
                // Идентификатор дополнительного свойства
            ->where('shop_item_properties.property_id', '=', 95)
                // Значание дополнительного свойства
            ->where('property_value_ints.value', '=', $city);
        $ch++;
     }
    
     if($photo) {
        if($flag)
             $Shop_Controller_Show->shopItems()->queryBuilder()->setOr();
        else
            $flag = true;
            
        $Shop_Controller_Show->shopItems()->queryBuilder()
                // Идентификатор дополнительного свойства
            ->where('shop_item_properties.property_id', '=', 84)
                // Значание дополнительного свойства
            ->where('property_value_files.file', '!=', '');
        $ch++;
     }
      
      
     if(isset($year_start) and $year_start > 0 and isset($year_end) and $year_end > 0 ) {
        
        if($flag)
             $Shop_Controller_Show->shopItems()->queryBuilder()->setOr();
        else
            $flag = true;
                        
        $Shop_Controller_Show->shopItems()->queryBuilder()
                // Идентификатор дополнительного свойства
            ->where('shop_item_properties.property_id', '=', 66)
                // Значание дополнительного свойства
            ->where('property_value_ints.value', '>=', $year_start)
            ->where('property_value_ints.value', '<=', $year_end);
            $ch++;
       }
        $Shop_Controller_Show->shopItems()->queryBuilder()->close();
      
        if(isset($price) and $price > 0 ) {  
         // Получаем список валют магазина
         $aShop_Currencies = Core_Entity::factory('Shop_Currency')->findAll();

         $query_currency_switch = 'price';
         
            $oShop = $Shop_Controller_Show->getEntity();
                        
            foreach ($aShop_Currencies as $oShop_Currency)
         {
            // Получаем коэффициент пересчета для каждой валюты
            $currency_coefficient = Shop_Controller::instance()->getCurrencyCoefficientInShopCurrency(
               $oShop_Currency, $oShop->Shop_Currency
            );

            $query_currency_switch = "IF (`shop_items`.`shop_currency_id` = '{$oShop_Currency->id}', IF (shop_discounts.percent, price * (100 - shop_discounts.percent) * {$currency_coefficient} / 100, shop_items.price * {$currency_coefficient}), {$query_currency_switch})";
         }

         $current_date = date('Y-m-d H:i:s');
         $Shop_Controller_Show->shopItems()
            ->queryBuilder()
            ->select(array(Core_QueryBuilder::expression($query_currency_switch), 'absolute_price'))
            ->leftJoin('shop_item_discounts', 'shop_items.id', '=', 'shop_item_discounts.id')
            ->leftJoin('shop_discounts', 'shop_item_discounts.id', '=', 'shop_discounts.id', array(
               array('AND (' => array('shop_discounts.end_datetime', '>=', $current_date)),
               array('OR' => array('shop_discounts.end_datetime', '=', '0000-00-00 00:00:00')),
               array('AND' => array('shop_discounts.start_datetime', '<=', $current_date)),
               array(')' => NULL)
            ));

            
            
            $Shop_Controller_Show->shopItems()->queryBuilder()->having('absolute_price', '<=', $price);
            $Shop_Controller_Show->addEntity(
               Core::factory('Core_Xml_Entity')
                  ->name('price_to')->value($price)
            );

         $Shop_Controller_Show->shopItems()->queryBuilder()
            ->clearOrderBy()
            ->orderBy('absolute_price', 'ASC');
      }
  
  
  
   $Shop_Controller_Show->shopItems()->queryBuilder()->groupBy('shop_items.id')->having('COUNT(shop_item_properties.id)', '=', $ch);
  
   $Shop_Controller_Show->shopItems()->queryBuilder()->where('shop_items.shop_group_id', 'IN', $neededGroups);                    
   $Shop_Controller_Show->show();

d-sant.com
Авторизация