문제

I have a custom module using which we can add banner images in admin. I have implemented this module in the admin successfully. Now I want to display banner in the front end.

My custom table is given below

table name : banner
     fields: banner_name  |  store_ids  |  images  |   img_path  |  status  

Store ids and Images are stored as comma-seperated-values. Now I want to select a banner item which corresponds to the current store view. Here is my code that I have tried to display banner module in the frontend.

<?php
    //get all active banner items as array
    $bannerItems = Mage::getModel('banner/banner') -> getCollection()
                -> addFieldToFilter('status',1) -> getItems(); //select only enabled items                  
    $curStoreId = Mage::app() -> getStore() -> getId(); //get current store id
    $banner = "";
    foreach($bannerItems as $item) 
    {    
         $data = $item -> getData();
         /*
             Store ids are saved as `comma separated values`. Hence making
             all store_ids as an array
         */
         $storearray = explode(",",$data['store_id']);
         foreach($storearray as $store)
         {                          
             if($store == $curStoreId) //check for matches, if yes load the item
             {               
                 $banner = $item;
                 break;               
             }

         }        
         if($banner != "") // ensure to store the first matched item to load
         {
             break;
         }

     }
     //output
     if( empty($banner) ) 
     {
         die("no banner exist for this store.Please add a banner !!!");
     }
     else
     {
         die( print_r( $banner->getId() ) );
     }
?>

This provide me banner model correspond for the current store view. However I feel that this code is lengthy. So I need to know how i can achieve this at its best. Please provide your suggestions. Thanks in advance

도움이 되었습니까?

해결책

I have not "tested" this but this should be helpful.

$currentStore = 5;

$bannerItems = Mage::getModel('banner/banner') -> getCollection()
            -> addFieldToFilter('status',1);
$bannerItems->getSelect()->where("FIND_IN_SET($currentStore, store_ids) > 0");
$bannerItems->getSelect()->orWhere("store_ids = 0");
$bannerItems->getSelect()->order("(FIND_IN_SET($currentStore, store_ids) > 0 ) * 10 DESC");

First find out the current store_id (1, used for example) using FIND_IN_SET and also look for store_ids =0, but sort the former result if exists in descending order so that you can get the required result at first row.

After that just use $bannerItems->getFirstItem(), everthing has been already done in the query.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 magento.stackexchange
scroll top