为了解决这个问题,我编写了能够执行所需更新的宏。
// Set a single value by dot notation key.
Collection::macro('set', function ($key, $new) {
$key = explode('.', $key);
$primary_key = array_shift($key);
$key = implode('.', $key);
$current = $this->get($primary_key);
if (!empty($key) && is_array($current)) {
array_set($current, $key, $new);
} else {
$current = $new;
}
$this->put($primary_key, $current);
});
// Increment a single value by dot notation key.
Collection::macro('increment', function ($key, $amount) {
$key = explode('.', $key);
$primary_key = array_shift($key);
$key = implode('.', $key);
$current = $this->get($primary_key);
if (!empty($key) && is_array($current)) {
$new = array_get($current, $key, 0);
$new += $amount;
array_set($current, $key, $new);
} else {
$current += $amount;
}
$this->put($primary_key, $current);
});
// Decrement a single value by dot notation key.
Collection::macro('decrement', function ($key, $amount) {
$key = explode('.', $key);
$primary_key = array_shift($key);
$key = implode('.', $key);
$current = $this->get($primary_key);
if (!empty($key) && is_array($current)) {
$new = array_get($current, $key, 0);
$new -= $amount;
array_set($current, $key, $new);
} else {
$current -= $amount;
}
$this->put($primary_key, $current);
});
有了这个,我需要做的就是:
$ads->increment($insight[$key] . '.spend', $insight[AdsInsightsFields::SPEND]);
如果我想简单地设置一个值,无论键是否存在,我都可以这样做:
$ads->set($insight[$key] . '.spend', $insight[AdsInsightsFields::SPEND]);