2

I have a custom module with a custom DB. The DB consist of customer_id field and inserted customer_id into it.

How can I get a single record based on customer_id passed, whereby customer_id is the unique field value in my DB table.

For example:

Mage::getModel('module/model')->addFieldToFilter('customer_id', array('eq' => $customerId));

The above code should give me a single record instead of giving a collection.

If I use below code:

Mage::getModel('module/model')->getCollection()->addFieldToFilter('customer_id', array('eq' => $customerId));

it gives me a record in array, and I do not want to use a loop to fetch data.

Is it possible to load data by using my custom DB field name, like

$custommoduleobj= Mage::getModel(‘yourmodulename/modelname’)->loadByCustomerId($customerId);

Please Help.

Thanks.

6

Try this:

Mage::getModel('module/model')->addFieldToFilter('customer_id', array('eq' => $customerId))->getFirstItem();

or this:

Mage::getModel('module/model')->load($customerId, 'customer_id');
  • Silly me..I knew it already, but didn't think about using it. Thanks. – Jordan Aug 21 '14 at 6:13
  • Marius,can you tell me,are you consider customer_id' is customer_id as table primary key – Amit Bera Aug 21 '14 at 7:44
  • @AmitBera In both the approaches above it's not important if customer_id id PK or not. – Marius Aug 21 '14 at 7:58
  • that means... if i have field firstname in this table...then i can one row using Mage::getModel('module/model')->load($customerfirstname, 'firstname'); – Amit Bera Aug 21 '14 at 8:04
  • Yes. But if the field is not unique there is no way to predict what row you get. – Marius Aug 21 '14 at 8:08
1

yes Possible... add this function on Model/Yourmodel.php

 public function loadByCustomerId($customerID)
    {
        $this->_getResource()->loadByCustomerId($this, $customerID);
        return $this;
    }

And then goto...Yourmodel.php class resource class at /Model/Mysql4/Resource ->Yourmodel.php

  public function ByCustomerId(YourmoduleNamesPace_YourmOdules_Model_YourModuel $Object, $customerId)
    {
        $adapter = $this->_getReadAdapter();
        $bind    = array('customer_id'  => $customerId);
        $select  = $adapter->select()
            ->from('yourtable' array('table_primary_key'))
            ->where('customer_id = :customer_id');


        $customerId = $adapter->fetchOne($select, $bind);
        if ($customerId) {
            $this->load($Object, $customerId);
        } else {
            $customer->setData(array());
        }

        return $this;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.