【问题标题】:Magento: select from databaseMagento:从数据库中选择
【发布时间】:2011-03-12 22:52:07
【问题描述】:

我正在为 magento 版本 1.3.2.3 开发我的第一个模块。 我创建了一个简单的表(不是 EAV,只是一个主键和 2 列)和一些访问它的类,遵循 Alan Storm's articles 这对我有很大帮助,但我不知道如何进行简单的选择:Alan解释如何使用主键加载,但不选择匹配某个值的行。

普通 MySQL 中我会写:

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

我找到了一个 sn-p,它给了我想要的结果:

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

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

【问题讨论】:

    标签: php oop mysql magento


    【解决方案1】:

    您可能想为此使用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());
    

    【讨论】:

    • 嗨艾伦,感谢您的回答。我尝试了您的解决方案,它也有效,但在这种情况下,我知道结果是单行,我认为 silvo 的解决方案更好。虽然第一种和最后一种方法很有趣,但我会记住它们。
    • @Refilon 听起来你想问一个新问题,而不是评论一个旧问题
    • 稍微修正一下:一定是getModel,而不是getMode
    【解决方案2】:

    这是一个如何在 CoreUrlRewrite 模型类中实现的示例:

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

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

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

    【讨论】:

      猜你喜欢
      • 2012-01-01
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      • 2016-12-17
      • 1970-01-01
      • 2014-07-05
      • 2013-04-26
      相关资源
      最近更新 更多