42.数据库 SQL 操作

1. $model->getResource() 方法:

$model = Mage::getModel('news/news');
$resourceModel= $model->getResource();

返回出一个资源(Resource)模型类

2.getTable() 方法

        $model = Mage::getModel('news/news');
        $resourceModel = $model->getResource();
        $table = $resourceModel->getMainTable();
        $table2 = $resourceModel->getTable('news/test1');
        var_dump($table); // news
        var_dump($table2); // test1_1

这里写图片描述


3.$resourceModel->getReadConnection();
Magento_Db_Adapter_Pdo_Mysql’

1、 fetchAll()  
//单次 select 查询 - 以多维数组形式返回出数据表中的所有数据
//例: 'select * from `table_name`', 用该方法来获取所有数据

2、 fetchRow()
//单次 select 查询 - 返回数据表中的一行数据
//例: "select * from `table` where `id` = ’1′", 用该方法来获取单条数据

3、 fetchCol()
//单次 select 查询 - 返回数据表中的一列数据
//例: "select `name` from `table`", 用该方法来获取单条数据

4、 fetchOne()
//单次 select 查询 - 返回数据表中单一的值
//例: "select count(*) from `table`", 我们就会用到该方法来获取单条数据
  $result = $this->_getReadAdapter()->fetchOne(
                'SELECT `user` FROM `table` WHERE `user` = :greatman',
                array('greatman' => 'shawn')
  );
  echo "$result";
$model = Mage::getModel('news/news');
        $resourceModel = $model->getResource();
        $adapter = $resourceModel->getReadConnection();//Magento_Db_Adapter_Pdo_Mysql

        $sql = 'select * from `news`';
        $a = $adapter->fetchAll($sql);

        var_dump($a);
        $sql1 = 'select * from `news` where `news_id`=1';
        $aa = $adapter->fetchRow($sql1);
        var_dump($aa);

        $sql2 = 'select * from `news` ';
        $aaa = $adapter->fetchCol($sql2);
        var_dump($aaa);

        $sql3 = 'select * from `news` where `news_id`=:id ';
        $aaaa = $adapter->fetchOne($sql3,array('id'=>1));
        var_dump($aaaa);

这里写图片描述


quoteInto()

//"user_id = 3″
$this->_getReadAdapter()
     ->quoteInto("user_id = ?", 3);

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

//如果含有多个 WHERE 的时候
$this->_getReadAdapter()->quoteInto("$field = ? AND ", $value)
     .
     $this->_getReadAdapter()->quoteInto("$field1 = ? OR ", $value1)
     .
     $this->_getReadAdapter()->quoteInto("$field2 = ?", $value2);
$a = $adapter->quoteInto('id=?',2);
        var_dump($a);

        $aa = $adapter->quoteInto('id=in(?)',array(1,2));
        var_dump($aa);

这里写图片描述


from()

$select = $this->_getReadAdapter()
               ->select()
               ->from($table, array('test_id'))
               ->where($where);
我们通过调用 select() 方法来获得到 select 对象,同时创建 select 查询, 然后它继续调用了 from() 方法

from($name, $cols = ‘*’, $schema = null) 方法

from() 这个方法带有多个参数,如果你只想执行 “select * from ” 语句, 你可以只填写第一个参数 from($table)

如果你想选择一列 test_id, 那么第二个参数就有用了, 同样的,如果想选择多列, 方法如下:
//单列 "select `test_id` from $table"
from($table, array('test_id'));

//多列 "select `test_id`, `col1`, `col2` from $table"
from($table, array('test_id', 'col1', 'col2'));

//多列带AS "select `test_id` as id, `col1` as column1 from $table"
from($table,array('id'=>'test_id', 'column1'=>'col1'));

还有,如果你想要输出自己刚写的 sql 语句,可以直接输出句柄

echo $select; 
$model = Mage::getModel('news/news');
        $resourceModel = $model->getResource();
        $adapter = $resourceModel->getReadConnection();//Magento_Db_Adapter_Pdo_Mysql

        $table = 'news';
        $a = $adapter->select()->from($table,array('news_id'));
        echo $a;
        echo '<br/>';

        $aa = $adapter->select()->from($table,array('news_id','title'));
        echo $aa;

这里写图片描述


select 对象

select() 方法返回出一个 select 对象,该对象为我们提供了很多方法来执行 sql 语句, 其父类便是 Varien_Db_Select, 你可以在其类中找到更多的方法来更深一步的操作, 现在我们来看一个简单的php代码
public function getAll()
{
    $table  = $this->getMainTable();
    $where  = $this->_getReadAdapter()
                   ->quoteInto("id = ?", 123);

    $select = $this->_getReadAdapter()
                   ->select()
                   ->from($table)
                   ->columns(array('test_id'))
                   ->where($where)
                   ->limit(10,5)
                   ->order('created_time')
                   ->group('list_id')
                   ->having('list_id > ?', 10);    
    echo $select;
}
从上你可以看出,这些方法都是来自于 select 对象, 并且都返回出自己所在的对象,这样的操作可以便于我们把多个方法串在一起

现在让我们来逐个温习
1select()
//用来初始化 sql 语句操作, 返回出一个 select 对象, 基于这个对象,我们可以做更多的操作

2、 from($name, $cols = '*', $schema = null)
//用来选择数据表的名字, 此时 select 已经初始化完成

3、 columns($cols = '*', $correlationName = null)
//通过这个方法你可以指定列名

4where($cond, $value = null, $type = null)
//用来声明 where 语句

5、 limit($count = null, $offset = null)
//第一个参数代表想要返回多少条数据, 第二个参数代表 offset 偏移量
//在上面代码中就是: LIMIT 10 OFFSET 5, 而不是 LIMIT 10,5

6order($spec)
//用来排序你所得的结果, 默认是: ascending
//如果想要是 descending, 可以写成 order(array('created_time' => Zend_Db_Select::SQL_DESC))

7group($spec)
//相当于 group by 语句

8、 having($cond, $value = null, $type = null)
//用来对 group by 语句的一个补充

Joins 方法

继续来看一个简单的方法

public function joinUs()
{
    $table  = $this->getMainTable();
    $table2 = $this->getTable('customer/entity');
    $cond   = $this->_getReadAdapter()
                   ->quoteInto('t1.id = t2.customer_id','');
    $where  = $this->_getReadAdapter()
                   ->quoteInto('t1.list_id = ?', '123');

    $select = $this->_getReadAdapter()
                   ->select()
                   ->from(array('t1'=>$table))
                   ->join(array('t2'=>$table2), $cond)
                   ->where($where);
    echo $select . "<br/>";

    $select = $this->_getReadAdapter()
                   ->select()
                   ->from(array('t1'=>$table))
                   ->joinLeft(array('t2'=>$table2), $cond)
                   ->where($where);
    echo $select . "<br/>";

    $select = $this->_getReadAdapter()
                   ->select()
                   ->from(array('t1'=>$table))
                   ->joinRight(array('t2'=>$table2), $cond)
                   ->where($where);
    echo $select . "<br/>";
}

这是我输出所得的结果

SELECT `t1`.*, `t2`.* FROM `szh` AS `t1` 
INNER JOIN `customer_entity` AS `t2` 
ON t1.id = t2.customer_id 
WHERE (t1.list_id = '123')

SELECT `t1`.*, `t2`.* FROM `szh` AS `t1` 
LEFT JOIN `customer_entity` AS `t2` 
ON t1.id = t2.customer_id 
WHERE (t1.list_id = '123')

SELECT `t1`.*, `t2`.* FROM `szh` AS `t1` 
RIGHT JOIN `customer_entity` AS `t2` 
ON t1.id = t2.customer_id 
WHERE (t1.list_id = '123')

COUNT,MAX 方法

继续来看一个简单的方法

public function countUs()
{
    $table  = $this->getMainTable();
    $where  = $this->_getReadAdapter()
                   ->quoteInto("id = ?", 123);

    $select = $this->_getReadAdapter()
                   ->select()
                   ->from($table)
                   ->reset('columns')
                   ->columns(new Zend_Db_Expr('count(*)'));
    echo $select . '<br>';

    $select = $this->_getReadAdapter()
                   ->select()
                   ->from($table)
                   ->reset('columns')
                   ->columns(new Zend_Db_Expr('max(list_id)'));
    echo $select . '<br>';
}

所得的结果:

SELECT count(*) FROM `szh`
SELECT max("list_id") FROM `szh`

这里可以看出, 包括平均值等, 我们都可以采用 Zend_Db_Expr 类


query() 方法

如果你有一个十分复杂的 sql 语句, 你也可以直接使用 query() 方法来执行

$sql = '...复杂的 sql 语句...';
$this->_getReadAdapter()->query($sql);

UPDATE 和 DELETE 方法

public function updateUs()
{
    $table = $this->getMainTable();
    $where = $this->_getWriteAdapter()
                  ->quoteInto('id = ?', 1);

    $query = $this->_getWriteAdapter()
                  ->update($table, 
                           array('product_id' => 2, 'file_id' => 3),
                           $where
                    );
}

这里你可以看出如何来执行 Update(更新) 语句

UPDATE `szh` SET `product_id` = 2, `file_id` = 3 WHERE (id = 1)

至于 Delete(删除) 语句, 如下:

$this->_getWriteAdapter()
     ->delete($table, $where)
     ->limit(1);

P.S 你可以在其他文件,如: model, phtml等获得到 Read Adapter(适配器), 但为了更好的体现出你代码的规整性及效率, 建议在 Resource 文件里执行这些 sql 语句


http://www.sunzhenghua.com/magento-module-development-database-sql-operations

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值