php Magento:通过自定义字段获取我的模型记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24796707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:28:39  来源:igfitidea点击:

Magento: Get record of my model by custom Field

phpmagentomagento-1.7

提问by rayphi

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?

那可能吗?

回答by OSdave

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

回答by Karan Adhikari

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

回答by Amit Bera

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