loadByCode()如何在magento中工作

时间:2015-07-13 06:54:50

标签: magento

loadByCode()如何运作?我一直在为我的新项目添加一个模块,并且不知道如何使用给定代码的模型使用loadByCode方法。

1 个答案:

答案 0 :(得分:0)

当您查看magento模型类时,它会扩展Mage_Core_Model_Abstract实习生扩展Varien_Object

课程Mage_Core_Model_Abstract的功能类似于getId()load()save()delete()等...

Mysql4个资源文件用于对表执行数据库查询。

假设我们有文件Keyur_Test_Model_Mysql4_Test资源文件。

<?php
class Keyur_Test_Model_Mysql4_Test extends Mage_Core_Model_Mysql4_Abstract
{
    public function _construct()
    {   
        $this->_init('test/test', 'test_id');
    }
    public function loadByField($field,$value){
        $table = $this->getMainTable();
        $where = $this->_getReadAdapter()->quoteInto("$field = ?", $value);
        $select = $this->_getReadAdapter()->select()->from($table,array('test_id'))->where($where);
        $id = $this->_getReadAdapter()->fetchOne($sql);
        return $id;
    }
}

这是模型文件Keyur_Test_Model_Test

<?php
class Keyur_Test_Model_Test extends Mage_Core_Model_Abstract
{
    public function _construct()
    {
        parent::_construct();
        $this->_init('test/test');
    }
    public function loadByField($field,$value){
        $id = $this->getResource()->loadByField($field,$value);
        $this->load($id);
    }
}

在此文件中,有许多新功能已被使用。让我们一个接一个。在我们的模型文件中,我们使用了这个函数 -

$id = $this->getResource()->loadByField($field,$value);

$this->getResource()函数返回资源模型的对象。所以我们只是在资源模型中调用loadyByField($field,$value)函数。

getTable()功能

现在在我们的Mysql4文件中,在loadByField()函数中我们使用了$table = $this->getMainTable();。这个函数返回当前模型的表名,即在类的构造函数中定义的表名。如果你想在magento中获取另一个sql表的表名,我们需要进行getTable()调用,例如

$table = $this->getTable(‘newsletter/subscribe’);

_getReadAdapter()功能

接下来我们有:  $where = $this->_getReadAdapter()->quoteInto(“$field = ?”, $value);

这里第一个函数也是$this->_getReadAdapter()函数。此函数返回一个具有执行数据库查询功能的对象,如fetch()fetchAll()query()等。

_quoteInfo()功能

我们使用的另一个函数是quoteInto():此函数用于创建where where条件。

在此,实际值被替换为我们编写的问号。例如,$this->_getReadAdapter()->quoteInto(“user_id = ?”, 3);转换为“user_id = 3”。

quoteInfo()的另一种常用变体是

$where = $this->_getReadAdapter()->quoteInto("$field IN(?)", array(1,2,3));

这会转换为“field in (1,2,3)

深入了解quoteInto()函数:如果我们有多个条件可供我们使用

$where = $this->_getReadAdapter()->quoteInto("$field = ? AND ", $value).$this->_getReadAdapter()->quoteInto("$field1 = ? OR ", $value1).$this->_getReadAdapter()->quoteInto("$field2 = ?", $value2);

继续我们的资源模型中的loadByField函数,接下来我们有

$select = $this->_getReadAdapter()->select()->from($table,array(‘test_id’))->where($where); 

这里我们使用select()和on()函数创建了select查询。

from()功能

from()函数有很多不同的参数,如果你想激活一个简单的select *查询,你只需要传递像from($table)这样的表名。

但是现在,我想只选择一个test_id列,所以我传递了一个列名为

的数组
 select. i.e array(‘test_id’).

如果我们想要选择多个列,我们需要array(‘test_id’,’col1’,’col2’)

这将创建一个像“select table_id,col1,col2 from $ table”的sql。

但支持我们想要一个SQL查询,例如“选择test_id作为id,col1作为来自$ table的column1”,我会调用 -

from($table,array('id'=>'test_id','column1'=>'col1'));