Yii2: update field with query builder

前端 未结 6 822
Happy的楠姐
Happy的楠姐 2021-01-07 17:26

How can I update field with query builder in Yii2? I can\'t find this in documentation.

Thanks!

UPD

This is the solution:

         


        
相关标签:
6条回答
  • 2021-01-07 17:36

    Query builder is for select queries only (sum, max, count too). You should use other methods - AR or raw queries (https://github.com/yiisoft/yii2/blob/master/docs/guide/db-dao.md#basic-sql-queries)

    0 讨论(0)
  • 2021-01-07 17:37
     Yii::$app->db->createCommand()
             ->update('customer', ['otp' => $otp_rand], ['custid' => 23])
             ->execute();
    

    **this is the right syntax and works & tested in yii2 **

    0 讨论(0)
  • 2021-01-07 17:43

    Try like this,

     Yii::$app->db->createCommand()
            ->update('table_name', [SET_Values], 'CONDITION')
            ->execute();
    

    For Example,

     Yii::$app->db->createCommand()
                 ->update('users', ['status' => 1], 'age > 30')
                 ->execute();
    
    0 讨论(0)
  • 2021-01-07 17:43

    If you have mpre then one condition then use this

    $this->localdb->createCommand()
        ->update(
            $this->MYTable,
            [
                'name' => $el['new'],
                'data' => $el['data'],
            ],
            [
                'userId' => $this->user,
                'product_id' => $this->productId,
                'name' => $el['old'],
                'created' => $el['date'],
                'category' => $el['cat'],
            ]
    
        );
    
    0 讨论(0)
  • 2021-01-07 17:57

    Also, if you need to use the column itself in the update query, you must use yii\db\Expression.

    \Yii::$app->db->createCommand()
        ->update('user', ['visits' => new \yii\db\Expression('visits + 1')], 'age > 30')
        ->execute();
    
    0 讨论(0)
  • 2021-01-07 17:59

    Create command can be used directly as follows :

    \Yii::$app->db->createCommand("UPDATE table SET column1=:column1, column2=:column2 WHERE id=:id")
    ->bindValue(':id', your_id)
    ->bindValue(':column1', :column1_value)
    ->bindValue(':column2', :column2_value)
    ->execute();
    
    0 讨论(0)
提交回复
热议问题