Подтвердить что ты не робот

Magento: получить запись моей модели по пользовательскому полю

Можно ли записать запись моей модели другим полем моей модели?

Обычный способ

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

Но мне нужно что-то вроде этого

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

возможно?

4b9b3361

Ответ 1

$model = Mage::getModel('foo_bar/baz');
$model->load('field_value', 'field_name');

Ответ 2

Перейти к файлу модели

NameSpace/Yourmodule/Model/YourModel.php

добавьте ниже код

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

И

NameSpace/YourModule/Model/Resource/YourModel.php

и код

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;
}

Ответ 3

используйте этот

$_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');