Magento model

某个字段保存不了 entity/customer _getDefaultAttributes添加字段名

$customer = Mage::getModel('customer/customer')->load(1);	
$customer->setData('is_charge', '2');
$customer->save(); //is_charge保存不成功原因

对某个字段进行算法操作或函数操作用new Zend_Db_Expr

array('point'=>new Zend_Db_Expr('pd.value*2'))

model/customer/customer.php

Mage::getSingleton('customer/customer')->setWebsiteId(Mage::app()->getStore()->getWebsiteId())->loadByEmail('demo@demo.com');

Model的启用,可以用Model下的文件 etc/config.xml

<models>
	<ticket>
		<class>Test_Ticket_Model</class>
		<resourceModel>ticket_mysql4</resourceModel>
	</ticket>
</models>

CURD操作:

public function createNewPostAction() { 
	$blogpost = Mage::getModel('ticket/log'); 
	$blogpost->setTitle('Code Post!'); 
	$blogpost->setPost('This post was created from code!'); 
	$blogpost->save(); 
	echo 'post created'; 
}

public function editFirstPostAction() { 
	$blogpost = Mage::getModel('ticket/log'); 
	$blogpost->load(1); //load($id, $field=null)   $filed = '键值'
	$blogpost->setTitle("The First post!"); 
	$blogpost->save(); 
	echo 'post edited'; 
}

public function deleteFirstPostAction() { 
	$blogpost = Mage::getModel('ticket/log'); 
	$blogpost->load(1); 
	$blogpost->delete(); 
	echo 'post removed'; 
}
//查询(select)语句
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
$select = "select * from table;"
//$select = $connection->select()->from('table', array('*')) ;
$rowsArray = $connection->fetchOne($select); // return row index0
$rowArray =$connection->fetchRow($select);   //return row

//插入(insert)语句
$fields = array();
$fields['name']= 'test';
$connection->insert('tablename', $fields);

//更新(update)语句
$connection->beginTransaction();
$fields = array();
$fields['name'] = 'jony';
$where = $connection->quoteInto('id =?', '1');
$connection->update('tablename', $fields, $where);
$connection->commit();

//删除(delete)语句
$condition = array($connection->quoteInto('id=?', '1'));
$connection->delete('tablename', $condition);

注意上面的getConnection()方法中的参数 "core_read",表明了Magento将要使用的资源。与之相对应,当我们修改数据库的时候使用参数"core_write".一般情况下 getConnection方法的参数应设成"core_read" 或 "core_write"(应该不指定也是可以的,但是如果Magento有多个数据库就必须指定了 )。对应上面新增的module的名字.使用下面相对应的语句在read或write Database:

$conn = Mage::getSingleton('core/resource')->getConnection('ticket_read');
$conn = Mage::getSingleton('core/resource')->getConnection('ticket_write');

local\Test\Ticket\etc\config.xml  model添加资源模型和实体对象,可以用Model\Mysql4下的文件

<global>
	<models>
		<ticket>
			<class>Test_Ticket_Model</class>
			<resourceModel>ticket_mysql4</resourceModel>
		</ticket>
		<ticket_mysql4>
			<class>Test_Ticket_Model_Mysql4</class>
			<entities>
				<log><!--model name-->
					<table>ticket_log</table><!-- table name-->
				</log>
				<type>
					<table>ticket_type</table>
				</type>
				<ticket>
					<table>ticket</table>
				</ticket>
			</entities>
		</ticket_mysql4>
	</models>
   <resources>
		<ticket_write>
			<connection>
				<use>activity_setup</use>  <!-- config  app\etc\config.xml-->
			</connection>
		</ticket_write>
		<ticket_read>
			<connection>
				<use>activity_setup</use>
			</connection>
		</ticket_read>
	</resources>
</global>

app\etc\config.xml

<resources>
****
	</core_read>

	<activity_setup><!-- new -->
		<connection>
			<host>localhost</host>
			<username>root</username>
			<password>Test</password>
			<dbname>Test_activity</dbname>
			<model>mysql4</model>
			<initStatements>SET NAMES utf8</initStatements>
			<type>pdo_mysql</type>
			<active>1</active><!-- 是1 -->
		</connection>
	</activity_setup>
</resources>
<resource>
	<connection>
		<types>
			<pdo_mysql>
				<class>Mage_Core_Model_Resource_Type_Db_Pdo_Mysql</class>
			</pdo_mysql>
		</types>
	</connection>
</resource>

local\Test\Ticket\Model\Log.php

<?php
class Test_Ticket_Model_Log extends Mage_Core_Model_Abstract
{
    public function _construct()
    {
        parent::_construct();
        $this->_init('ticket/log');
    }

    public function saveInfo($rewriteData)
    {
        return $this->getResource()->saveWeiboData($rewriteData);
    }

    public function getLastRechargeReal($customerId, $rechargeType) //array
    {
        return $this->getResource()->getLastRechargeReal($customerId, $rechargeType);
    }
    public function getRecommendProducts()  //object
    {
        if (!$this->getId()) {
            return array();
        }
    
        $array = $this->getData('recommend_products');
        if (is_null($array)) {
            $array = $this->getResource()->getRecommendProducts($this);
            $this->setData('recommend_products', $array);
        }
        return $array;
    }
    public function saveCardInfo($cardNo)
    {
        try {
            /*开始事务*/
            $this->getResource()->beginTransaction();

            $customer = Mage::getSingleton('customer/session')->getCustomer();
            $oldcard = $customer->getData('idcard');
            #更新卡状态为绑定
            $idcard = $this->loadByCardno($cardNo);
            $idcard->setData('idcard_status', self::IDCARD_STATUS_BINDING);
            $idcard->save();

            #更新用户的ID卡
            $customer->setData('idcard', $cardNo);
            $customer->save();

            $this->getResource()->commit();
        } catch (exception $e) {
            $this->getResource()->rollBack();
        }
    }
}

Mysql4  local\Test\Ticket\Model\Mysql4\Log.php

<?php
class Test_Ticket_Model_Mysql4_Log extends Mage_Core_Model_Mysql4_Abstract {
    public function _construct() {
        //$this->_setResource(array('read' =>'ticket_read', 'write' =>'ticket_write'));//多数据库
        $this->_init('ticket/log', 'id'); #主键
    }

    public function getLastRechargeReal($customerId, $rechargeType) {
        $sql = $this->_getReadAdapter()->select()->from($this->getMainTable(), array('customer_id'))
            ->where('customer_id = ?', $customerId)
            ->where('recharge_type = ?', $rechargeType)
            ->order(array('id DESC'))
            ->limit(1);

        return $this->_getReadAdapter()->fetchRow($sql);
    }

    //联表查询
    public function getAttributesUsedInListing() {
        $sql = $this->_getReadAdapter()->select()
            ->from(array('main_table' => $this->getMainTable()))
            ->join(array('additional_table' => $this->getTable('catalog/eav_attribute')),
            'main_table.attribute_id = additional_table.attribute_id',
            array())
            ->joinLeft(array('al' => $this->getTable('eav/attribute_label')),
            'al.attribute_id = main_table.attribute_id AND al.store_id = ' . (int)$this->getStoreId(),
            array('store_label' => new Zend_Db_Expr('IFNULL(al.value, main_table.frontend_label)')))
            ->where('additional_table.used_in_product_listing=?', 1);

        // $sql = $sql->assemble();
        // echo $sql;
        return $this->_getReadAdapter()->fetchAll($sql);
    }

    public function saveInfo($rewriteData) {
        $this->_getWriteAdapter()->insert($this->getMainTable(), $rewriteData);
        return $this->_getWriteAdapter()->lastInsertId();
    }

    public function updateInfo($id, $rewriteData) {
        $this->_getWriteAdapter()->update($this->getMainTable(), $rewriteData, $this->_getWriteAdapter()->quoteInto($this->getIdFieldName() . '=?', $id));
    }

    public function test() {
        $sql = 'update ' . $this->getMainTable() . " set a=1 where id=1";
        return $this->_getReadAdapter()->query($sql);
        //$this->beginTransaction();
 $this->_getWriteAdapter()->delete($this->getMainTable(), array("email='$email''", "type='$type'"));
        //$this->_getWriteAdapter()->delete($this->getMainTable(), $this->_getWriteAdapter()->quoteInto($this->getIdFieldName().'=?', $id));
    }

    public function count() {
        $table = $this->getMainTable();
        $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>';
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值