Friday, November 20, 2009

Re: Increment value using CakePHP model functions

It's possible in two ways.

First, you've got the `updateAll` function which doesn't escape or
mess with your arguments:

$this->Item->updateAll(
array('Item.flags' => 'Item.flags + 1'),
array('Item.id' => 666)
);

One possible problem with this is that it will not call `afterSave`,
trigger behaviour methods, etc... because it's not really a save.
If you need this to work with the rest, the solution is a bit more
long-winded:

$db =& ConnectionManager::getDataSource($this->Item->useDbConfig);
$this->Item->set('flags', $db->expression('`Item`.`flags`+1'));
$this->Item->save();

In reality, accessing the datasource and whatnot should be hidden in
the model, but this shows a bare-bones way of getting it working.

hth
grigri

On Nov 20, 12:46 pm, Dave <davidcr...@gmail.com> wrote:
> Hi everybody,
>
> I have a quick question that bugs me each time I run into it in a project,
> and then I promptly forget about it.  It is an easy fix, but it is such
> common functionality that I feel there must be some way to do it within
> built in functions rather then a custom query.
>
> The issue is incrementing a table field without grabbing the previous value,
> using MySQL's default function `tablefield` = `tablefield` + 1 .
>
> example:
>
> $this->Item->query('UPDATE `items` SET `flags` = `flags`+1 WHERE
> `items`.`id` = ' . $id);
>
> I have tried pretty much every way I can think of with model->saveField to
> accomplish this through cake, but I can't get it to work.
>
> First I set the id with $this->Item->id = $id
> After that I have tried
>
> $this->Item->saveField('flags','+1');
> $this->Item->saveField('flags',' +1');
> $this->Item->saveField('flags', 'flags+1');
> $this->Item->saveField('flags', '`flags`+1');
>
> So... is there a way to do this with 1 query within cake? I like to have as
> few custom queries as possible within my application.
>
> Thanks for any tips,
>
> who knows, if it isn't built in maybe I will be able to make my first
> contribution to the Core!
>
> Dave

--

You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com.
To unsubscribe from this group, send email to cake-php+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/cake-php?hl=.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate