数据插入、更新、删除、统计

 


 

更新数据

方法

 

update(array $data, $where, $table = '')

 

返回值

 

成功:返回影响函数,影响行数有可能为0
失败:返回false
判断返回值不全等于false就表示更新成功$result !== false

 

自增自减

 

$data = [
    'view_num' => ['+', 1]
];
SQL: SET view_num = view_num + 1
具体加多少,你自己定,比如,加9
'view_num' => ['+', 9]

 

例子

 

<?php
namespace common\model\user;

use common\model\WebModel;

class UserModel extends WebModel
{
    public function demoUpdate()
    {
        $data = array(
            'phone' => '13900008888',
            'integral' => ['+', 10],
            'balance' => ['-', 100],
        );
        $ret = $this->update($data, array('uid' => 10008));
        if ($ret === false) {
            return $this->result(1, '更新失败');
        }
        return $this->result(0, '更新成功');
    }
}

 

自增、自减

inc($field, $step = 1)
dec($field, $step = 1)

 

$id = 101;
$archiveModel = new ArchiveModel();
$archiveModel->where($id)->inc('view_num');
$archiveModel->where($id)->inc('view_num', 2);

 

插入数据

方法

 

insert(array $data, $table = '')

 

插入当前模型对应的表,比如: timo_user

 

返回值

 

成功:返回插入的自增主键ID的值,如果表主键不是自增的,那么,返回插入的主键的值

失败:返回false

 

<?php
namespace common\model\user;

use common\model\WebModel;

class UserModel extends Model
{
    public function addUser($phone, $email, $user_name)
    {
        $data = array(
            'phone' => $phone,
            'email' => $email,
            'user_name' => $user_name,
        );
        $user_id = $this->insert($data);
        if (!$user_id) {
            return false;
        }
        return true;
    }
}

 

插入另外一张表,如插入timo_user_extends表,记得要加表前缀

 

$t_user_extends = 'timo_user_extends';
$data = array(
    'uid' => 1000001,
    'birthday' => 1487795904,
);
$this->insert($data, true, $t_user_extends);

 

批量插入

 

/**
 * 批量插入数据
 *
 * @param array $data
 * @param bool $return_id
 * @param string $table
 * @return bool|int
 */
public function insertMulti(array $data, $return_id = true, $table = '')

 

删除数据

 

/**
 * 删除数据
 *
 * @param string|array $where
 * @param string $table
 * @return bool
 */

 

public function delete($where, $table = '')

 

<?php
namespace common\model\user;

use common\model\WebModel;

class UserModel extends WebModel
{
    public function deleteUser($uid)
    {
        $where = array(
            'uid' => $uid
        );
        $ret = $this->delete($where);
        if (!$ret) {
            return $this->result(1, '删除失败');
        }
        return $this->result(0, '删除成功');
    }
}