Magento:通过自定义Field获取我的模型记录

时间:2014-07-17 06:52:48

标签: php magento magento-1.7

是否有可能通过我的模型的另一个字段记录我的模型?

正常的方式

$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

可能吗?

3 个答案:

答案 0 :(得分:51)

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

答案 1 :(得分:1)

转到模型文件

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

答案 2 :(得分:1)

使用此

$_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');  
相关问题