Home  >  Article  >  Database  >  yii2 + mysql 常用增删改查操作语法以及事务

yii2 + mysql 常用增删改查操作语法以及事务

WBOY
WBOYOriginal
2016-06-07 15:35:201683browse

关于数据库mysql的使用: 1.查询: Salesorderitem::find()-asArray()-where([order_id=$order_id])-all();Salesorderitem::find()-asArray()-where([order_id=$order_id])-one();Quote::findOne([customer_id = $customer_id]); 2.插入: $order = new S


关于数据库mysql的使用:

1.查询:

Salesorderitem::find()->asArray()->where(['order_id'=>$order_id])->all();

Salesorderitem::find()->asArray()->where(['order_id'=>$order_id])->one();

Quote::findOne(['customer_id' => $customer_id]);


2.插入:

$order = new Salesorder();

$order->order_status = $order_status;

$order->store = $store;

$order->save();

$order_id = Yii::$app->db->getLastInsertID();

 

$db->createCommand('INSERT INTO customer (name) VALUES (:name)', [    ':name' => 'Qiang',])->execute();


 

3更新:

3.1

 Yii::$app->db->createCommand()->update(self::QUOTE_ITEM, [

'qty' => $qty,

'row_weight'=>$row_weight,

'base_row_total'=>$base_row_total,

'row_total'=>$row_total,

], 

'quote_id='.self::$_quote_id.' and item_id='.$item_id  )

->execute();


3.2// to update an existing customer record

$customer = Customer::findOne($id);

$customer->email = 'james@example.com';

$customer->save();  


// equivalent to $custmer->update();

4. 删除:

Quoteitem::deleteAll('quote_id='.self::$_quote_id.' and  item_id='.$item_id);


注:使用mysql的时候一定要注意sql注入攻击的屏蔽


# 开始事务

  $innerTransaction = Yii::$app->db->beginTransaction();
        try {
            # 保存quoteitems
            self::removeQuoteItems($data['item_id']);
            # 获取quoteitems ,保存到 self::$_quote_items
            self::getQuoteItems();
            # 保存 quote
            self::saveQuote();
            $innerTransaction->commit();
        } catch (Exception $e) {
            $innerTransaction->rollBack();
        }




 


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn