Magento - 模块INSERT,UPDATE,DELETE,SELECT代码

Lim*_*eun 13 sql crud magento magento-1.7

我创建了一个模块,并希望使用核心写入和读取功能来插入,更新,删除或选择带条件的数据库值,如何在不使用SQL的情况下执行此操作?示例:$ customer_id = 123模型=(推荐/推荐)

选择

 $collection3 = Mage::getModel('referral/referral')->getCollection();
    $collection3->addFieldToFilter('customer_id', array('eq' => $customer_id));
    foreach($collection3 as $data1)
    {
    $ref_cust_id.= $data1->getData('referral_customer_id'); 
    }
Run Code Online (Sandbox Code Playgroud)

插入

$collection1= Mage::getModel('referral/referral');
$collection1->setData('customer_id',$customer_id)->save();
Run Code Online (Sandbox Code Playgroud)

DELETE,UPDATE(有条件)= ???

Dea*_*Man 25

假设,我有一个名为的模块mynews.这里如下的代码select, insert, update, and delete datanews表中.

INSERT DATA

$data包含要插入的数据数组.数组的键应该是数据库表的字段名,值应该是要插入的值.

$data = array('title'=>'hello there','content'=>'how are you? i am fine over here.','status'=>1);
$model = Mage::getModel('mynews/mynews')->setData($data);
try {
    $insertId = $model->save()->getId();
    echo "Data successfully inserted. Insert ID: ".$insertId;
} catch (Exception $e){
 echo $e->getMessage();   
}
Run Code Online (Sandbox Code Playgroud)

SELECT DATA

$item->getData() prints array of data from ‘news’ table.
$item->getTitle() prints the only the title field.
Run Code Online (Sandbox Code Playgroud)

同样,要打印内容,我们需要写$item->getContent().

$model = Mage::getModel('mynews/mynews');
$collection = $model->getCollection();
foreach($collection as $item){
print_r($item->getData());
print_r($item->getTitle());
}
Run Code Online (Sandbox Code Playgroud)

UPDATE DATA

$id是要更新的数据库表行id. $data包含要更新的数据数组.数组的键应该是数据库表的字段名称,值应该是要更新的值.

// $id = $this->getRequest()->getParam('id');
$id = 2;
$data = array('title'=>'hello test','content'=>'test how are you?','status'=>0);
$model = Mage::getModel('mynews/mynews')->load($id)->addData($data);
try {
    $model->setId($id)->save();
    echo "Data updated successfully.";

} catch (Exception $e){
    echo $e->getMessage(); 
}
Run Code Online (Sandbox Code Playgroud)

DELETE DATA

$id 是要删除的数据库表行id.

// $id = $this->getRequest()->getParam('id');
$id = 3;
$model = Mage::getModel('mynews/mynews');
try {
    $model->setId($id)->delete();
    echo "Data deleted successfully.";

} catch (Exception $e){
    echo $e->getMessage(); 
}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以在自定义模块和任何模块中执行选择,插入,更新和删除magento code.

资料来源:http://blog.chapagain.com.np/magento-how-to-select-insert-update-and-delete-data/