سؤال

I am writing a custom module, and in this module I need to add a search query to the database if it's not there already. I figured out what I need to do:

  1. Load catalogsearch/query model
  2. Check if query exists, if not add it

Here's the code I thought would work:

$querymodel = Mage::getModel('catalogsearch/query');
$querymodel->loadByQueryText('testing 123');

if (!$querymodel->getId()) {
    $querymodel->setIsActive(1);
    $querymodel->setQueryText('testing 123');
    $querymodel->setStoreId(1);
    $querymodel->setIsProcessed(0);
    $querymodel->save();
}

This code is successful in that it adds to the catalogsearch_query table. However the initial check loadByQueryText() or loadByQuery() simply does not return true even when a query exists - so I keep getting the same query added to the db.

I've looked through the model file (Catalogsearch/Model/Query.php) and I'm using the method in the exact same context as the model itself, so I don't know why it doesn't work?

Any help much appreciated!

هل كانت مفيدة؟

المحلول 3

I ended up getting it working in a less clean way - no idea why the loadByQueryText() method is stuill not working.

$querymodel = Mage::getModel('catalogsearch/query')
    ->getCollection()
    ->addFieldToFilter('query_text', 'testing 123')
    ->getFirstItem();

This returns a result so I'm gonna use it.

نصائح أخرى

You are able to tell Magento with field to use on load. The following code should allow you to tell catalogsearch/query to load by the query_text attribute.

$querymodel = Mage::getModel('catalogsearch/query');
$querymodel->load('test 123','query_text');

I've done the following in order to debug:

$querymodel = Mage::getModel('catalogsearch/query');
$querymodel->loadByQueryText('test');
$data = $querymodel->getData();
print_r($querymodel->getData());

And if the record exists, the output is:

Array
(
    [query_id] => 54120
    [query_text] => test
    [num_results] => 1
    [popularity] => 1
    [redirect] => 
    [synonym_for] => 
    [store_id] => 6
    [display_in_terms] => 1
    [is_active] => 1
    [is_processed] => 0
    [updated_at] => 2013-01-08 03:55:26
)

In your code if (!$querymodel->getId()) { should be if (!$querymodel->getQueryId()) { or look at the value returned by $querymodel->getData()

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى magento.stackexchange
scroll top