Welcome Guest, Not a member yet? Register   Sign In
Increment field with ActiveRecord
#1

[eluser]Alex007[/eluser]
It seems that with ActiveRecord it is impossible to increment the value of a field without fetching it first.

Here's what I'd like to do:
Code:
$this->db->where('ThreadId', $ThreadId);
$this->db->set('ViewCount = ViewCount + 1');
$this->db->update('Forum_Threads');
But that doesn't work, the resulting query looks something like this:
Code:
UPDATE Forum_Threads SET 'ViewCount = ViewCount + 1' = '' WHERE ThreadId = 1

Is there anyway, with ActiveRecord, to increment a field, without fetching it's value first ? I don't need to know the value at all, so SELECTing it first would be a waste of resources.

Do I have to resort to simple_query() ?
#2

[eluser]Tom Vogt[/eluser]
*bump* - I very much have the same problem. Is there a solution?
#3

[eluser]xwero[/eluser]
I reported a bug for the same problem. Derek said it is fixed in the svn and you have to use (update : it's still not in the svn code)
Code:
$this->db->set('ViewCount','ViewCount + 1',false);
The thirth argument is for escaping the value that has been set to true by default.

The code for the new set method is
Code:
function set($key, $value = '',$escape = true)
    {
        $key = $this->_object_to_array($key);
    
        if ( ! is_array($key))
        {
            $key = array($key => $value);
        }    

        foreach ($key as $k => $v)
        {
            $this->ar_set[$k] = ($escape)?$this->escape($v):$v;
        }
        
        return $this;
    }
#4

[eluser]Derek Allard[/eluser]
Sorry, its fixed, but hasn't made its way into the svn yet.

A few other things first... but very soon.
#5

[eluser]xwero[/eluser]
I saw there was an addition in the SVN of the raw_where and raw_or_where methods will the set method have something similar?
#6

[eluser]Derek Allard[/eluser]
Something similar yes.
#7

[eluser]xwero[/eluser]
The reason why i asked the question is because i'm concerned with the naming of the methods. If similar functionality has different methods of calling it gets confusing.

So actually i was asking is if the the raw_ prefix is going to be used or setting the (third) argument to false?
#8

[eluser]Derek Allard[/eluser]
Good point, it does seem inconsistent, to have set() use a parameter for no escaping, but a whole new function for where(). That said, in order to achieve the same thing with a parameter in where we'd need to make it

Code:
$this->db->where('(field1 = var1 OR field2 = var2)', NULL , FALSE);

And really, that's what raw_where() will be an alias for. I just think its less confusing.
#9

[eluser]delay[/eluser]
thanks xwero,

just tried the new set method with the new set query and it works well with incrementing/decrementing values.




Theme © iAndrew 2016 - Forum software by © MyBB