首頁  >  文章  >  資料庫  >  yii2 + mysql 常用增删改查操作语法以及事务

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

WBOY
WBOY原創
2016-06-07 15:35:201719瀏覽

关于数据库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();
        }




 


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn