是否有方法为某些内容增加视图表,或者如果不存在,则在不运行2个查询的情况下添加第一个视图。这是我当前有效的代码。
function increment_views($id = null) {
if ($id !== NULL) {
$record = array('id' => $id, 'views' => 'views+1');
// check exists
$query = $this->db->get_where('views', array('id' => $id), 1, 0);
if ($query->num_rows() == 0) {
// if !exists, insert
$db_view_data = array(
'id' => $id,
'views' => '1'
);
$this->db->insert('views', $db_view_data);
} else {
// A record does exist, update it.
$this->db->where('id', $id);
$this->db->set('views', 'views+1', false);
$this->db->update('views');
}
// check it worked
if ($this->db->affected_rows() > 0) {
return true;
}
return false;
}
return false;
}
您可以使用以下重复密钥来实现这一点:
$query = "INSERT into views(id,views)values($id,1) on DUPLICATE KEY UPDATE views=views+1;
希望这有帮助:)
我不确定您使用的是什么DB包装器,但是,您基本上想要执行以下单个SQL语句:
UPDATE table SET column = column + 1 WHERE id = ...;