当前位置:Gxlcms > mysql > yii2+mysql常用增删改查操作语法以及事务

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

时间:2021-07-01 10:21:17 帮助过:122人阅读

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




人气教程排行