Commit 19a489be authored by endi's avatar endi

Fix create/update methods

parent 435456cb
<?php namespace Terranet\Rankable;
<?php
namespace Terranet\Rankable;
trait HasRankableField
{
......@@ -42,13 +44,10 @@ trait HasRankableField
*/
public function syncRanking(array $ranking = [])
{
foreach((array) $ranking as $id => $value)
{
foreach ((array) $ranking as $id => $value) {
$this
->where($this->getKeyName(), '=', $id)
->update([
$this->getRankableColumn() => (int) $value
]);
->update([$this->getRankableColumn() => (int) $value]);
}
}
......@@ -56,51 +55,47 @@ trait HasRankableField
{
static::addGlobalScope(new RankableScope);
static::updating(function(Rankable $model)
{
if ($model->isDirty($model->getRankableColumn()) && $oldValue = $model->getOriginal($model->getRankableColumn()))
{
static::updating(function (Rankable $model) {
if ($model->isDirty($model->getRankableColumn()) && $oldValue = $model->getOriginal($model->getRankableColumn())) {
// switch ranks in conflicts
$query = $model->newQuery();
$query = $model->applyRankGrouping($query, $model);
$query = $model->rankableQuery($model);
$query->where($model->getRankableColumn(), '=', (int) $model->getAttribute($model->getRankableColumn()));
$query->update([
$model->getRankableColumn() => $oldValue
]);
$query->update([$model->getRankableColumn() => $oldValue]);
}
});
static::creating(function(Rankable $model)
{
static::creating(function (Rankable $model) {
$field = $model->getRankableColumn();
if (! $model->{$field})
{
$query = $model->newQuery();
$query = $model->applyRankGrouping($query, $model);
if (!$model->{$field}) {
$query = $model->rankableQuery($model);
$value = (int) $query->max($field);
$model->{$field} = ($value + $model->getRankableIncrementValue());
$model->setAttribute($field, $value + $model->getRankableIncrementValue());
}
});
}
protected function applyRankGrouping($query, $model)
{
if ($columns = (array) $model->getRankableGroupByColumn())
{
foreach($columns as $column)
{
if ($columns = (array) $model->getRankableGroupByColumn()) {
foreach ($columns as $column) {
$query->where($column, '=', $model->{$column});
}
}
return $query;
}
/**
* @param Rankable $model
* @return mixed
*/
protected function rankableQuery(Rankable $model)
{
return $model->applyRankGrouping($model->newQueryWithoutScopes(), $model);
}
}
\ No newline at end of file
<?php namespace Terranet\Rankable;
<?php
namespace Terranet\Rankable;
interface Rankable
{
......
......@@ -2,7 +2,7 @@
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ScopeInterface;
use Illuminate\Database\Eloquent\Scope as ScopeInterface;
class RankableScope implements ScopeInterface
{
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment