Magento:从数据库中选择

时间:2010-07-07 17:20:20

标签: php oop mysql magento

我正在研究magento 1.3.2.3版的第一个模块。 我创建了一个简单的表(不是EAV,只是一个主键和2列)和一些访问它的类,在Alan Storm's articles之后帮助了我很多,但我无法弄清楚如何进行简单的选择:Alan解释了如何使用主键加载,但没有选择与某个值匹配的行。

普通MySQL中我写道:

SELECT *  
FROM my_table  
WHERE some_field = '" . $someValue . "'  

我找到了一个片段,它给了我想要的结果:

$resource = new Mage_Core_Model_Resource();  
$read = $resource->getConnection('core_read');  
$select = $read->select()
               ->from('my_table')
               ->where('some_field = ?', $someValue);  
return $read->fetchAll($select);  

但是必须有一个更简单/更漂亮的解决方案,使用我创建的模型类。结果将是单行,而不是集合 我已经尝试了我能想到的一切,比如:

return Mage::getModel('modulename/classname')->select()->where('some_field = ?', $comeValue);
return Mage::getModel('modulename/classname')->load()->where('some_field = ?', $comeValue);  
return Mage::getModel('modulename/classname')->load(array('some_field = ?', $comeValue));  

以及更多的东西,但到目前为止没有运气:我错过了什么?

2 个答案:

答案 0 :(得分:7)

您可能希望使用your model's Collection

$collection = Mage::getModel('mygroup/mymodel')->getCollection();
$collection->addFieldToFilter('some_field',$some_value);

foreach($collection as $item)
{
    var_dump($item);
}

var_dump($collection->getFirstItem());
var_dump($collection->getLastItem());

答案 1 :(得分:6)

以下是在CoreUrlRewrite Model类中实现此目的的示例:

public function loadByIdPath($path)
{
    $this->setId(null)->load($path, 'id_path');
    return $this;
}

您可以在模型类中创建类似的方法。您还可以在代码中的任何位置使用替代形式的加载方法:

$model = Mage::getModel('modulename/classname')->load($someValue, 'some_field');