0

我使用的是 laravel v3.2.12-4,我遇到了递减函数的问题。此方法不是只更新一行,而是影响列中的所有行。我使用 Eloquent,我有一个 many_to_many 关系。

包含递减方法的代码是:

 foreach ($ids as $id) {
 $indicator = Indicator::find($id);
 $tags = $indicator->tags()->get();
 foreach ($tags as $tag) {

    $indicator->tags()->detach($tag->id);
    if ($tag->frequency == 1) {
        $tag->delete();
    } else {
        // I have to made  this code to fix the problem with decrement function
        // But i want to use decrement
        $tag->frequency = $tag->frequency - 1;
        $tag->save();

        // This dosnt work for me.
        // $tag->decrement('frequency');
    }
}

$indicator->delete();

}

在模型类指标中,我与这个函数建立了关系:

public function tags()
{
    return $this->has_many_and_belongs_to('Tag');
}

在模型类标签中,我与这个函数建立了关系:

public function indicators()
{
    return $this->has_many_and_belongs_to('Indicator');
}

好吧,如果我对列进行了更新,这个结果对我来说没问题,但是当我使用递减函数时,这会影响所有行,我不知道这是一个错误还是这个方法的问题。

谢谢。

4

1 回答 1

0

这就是它的设计方式。该decrement()方法实际上是在查询构建器上定义的,而不是在 Eloquents 构建器上。这意味着当您调用$tag->decrement('frequency')它时,它实际上是通过 QB 并简单地运行类似UPDATE tag SET frequency=frequency - 1. 注意没有 WHERE 子句?

您仍然可以使用该decrement()方法,但您必须这样做。

$tag->where_id($tag->id)->decrement('frequency');

现在你已经设置了 WHERE 子句,只有那个标签会被递减。当然,更清洁的解决方案就是您所拥有的。或者也许这个。

$tag->frequency--;

未经测试,可能会引发某种错误。

于 2013-04-11T12:50:39.763 回答