This repository has been archived on 2024-10-25. You can view files and clone it, but cannot push or open issues or pull requests.
Sequenzia/Rails/ActiveRecord/Base/Methods/CounterMethods.php

27 lines
825 B
PHP
Raw Normal View History

2013-10-02 08:12:58 +02:00
<?php
namespace Rails\ActiveRecord\Base\Methods;
trait CounterMethods
{
static public function incrementCounter($counter_name, $id)
{
return self::updateCounters([$id], [$counter_name => 1]);
}
static public function decrementCounter($counter_name, $id)
{
return self::updateCounters([$id], [$counter_name => -1]);
}
static public function updateCounters(array $ids, array $counters)
{
if (!is_array($ids))
$ids = [$ids];
$values = [];
foreach ($counters as $name => $value)
$values[] = "`" . $name . "` = `".$name."` " . ($value > 0 ? '+' : '-') . " 1";
$sql = "UPDATE `".self::tableName()."` SET ".implode(', ', $values)." WHERE id IN (?)";
return self::connection()->executeSql($sql, $ids);
}
}