13

Is it possible to get a record of my model by another field of my model?

The normal way

$model = Mage::getModel('foo_bar/baz');
$model->load($id);
// do something with the loaded record

But i need something like this

$model = Mage::getModel('foo_bar/baz');
$model->loadByAnotherFieldOfModel($value)
// do something with the loaded record

is that possible?

Phantom
  • 1,704
  • 4
  • 17
  • 32
rayphi
  • 503
  • 2
  • 14
  • 30

3 Answers3

55
$model = Mage::getModel('foo_bar/baz');
$model->load('field_value', 'field_name');
Spencer Williams
  • 821
  • 10
  • 20
OSdave
  • 8,538
  • 7
  • 45
  • 60
  • Okey that's to easy and to smart :D – rayphi Jul 18 '14 at 07:01
  • 2
    What if multiple row match the same field data ? For me its only returning one row or one record ? Is there a way to return the collection of rows matched the field data. – ted Jul 15 '15 at 10:13
  • @OSdave, Could you please replace $id with some meaningful variable name eg: $fieldName, just to clear up confusion. $model->load($fieldName, 'field_name'); – Vineet Sajwan Oct 18 '15 at 12:44
  • @vineetsajwan, you got it wrong. $id is the value that 'field_name' field should have, in order to load that record. – Mihai MATEI Nov 11 '15 at 10:12
  • @Mihai - Ok, actually I understood that way. – Vineet Sajwan Feb 15 '16 at 07:22
2

use this

$_category = Mage::getModel('catalog/category')->loadByAttribute('name', 'computer');  
$_product = Mage::getModel('catalog/product')->loadByAttribute('name', 'hp2312');  

// Load by SKU  
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku', 'computer123');  
Karan Adhikari
  • 352
  • 1
  • 12
1

Goto model file

NameSpace/Yourmodule/Model/YourModel.php

add below code

public function loadByField($fieldvalue)
{
  $this->_getResource()->loadByField($this, $fieldvalue);
  return $this;
}

AND

NameSpace/YourModule/Model/Resource/YourModel.php

and code is

public function loadByField(NameSpace_YourModule_Model_YourModel $Object, $fieldvalue)
{
  $adapter = $this->_getReadAdapter();
  $bind    = array('fieldname' => $fieldvalue);
  $select  = $adapter->select()
      ->from($this->getMainTable(), 'tablePrimaryKey')
      ->where('fieldname = :fieldname');

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

  return $this;
}
rayphi
  • 503
  • 2
  • 14
  • 30
Amit Bera
  • 7,581
  • 7
  • 31
  • 57