타임 스탬프를 건드리지 않고 업데이트 (Laravel)
타임 스탬프를 터치하지 않고 사용자를 업데이트 할 수 있습니까?
타임 스탬프를 완전히 비활성화하고 싶지 않습니다 ..
grtz
일시적으로 비활성화 :
$user = User::find(1);
$user->timestamps = false;
$user->age = 72;
$user->save();
저장 후 선택적으로 다시 활성화 할 수 있습니다.
이것은 Laravel 4 및 5 전용 기능 이며 Laravel 3에는 적용되지 않습니다.
Laravel 5.2
에서는 다음 과 같이 public 필드 $timestamps
를 설정할 수 있습니다 false
.
$user->timestamps = false;
$user->name = 'new name';
$user->save();
또는 옵션을 save()
함수 의 매개 변수로 전달할 수 있습니다 .
$user->name = 'new name';
$user->save(['timestamps' => false]);
작동 방식에 대한 더 깊은 이해를 \Illuminate\Database\Eloquent\Model
위해 메서드에서 클래스를 살펴볼 수 있습니다 performUpdate(Builder $query, array $options = [])
.
protected function performUpdate(Builder $query, array $options = [])
// [...]
// First we need to create a fresh query instance and touch the creation and
// update timestamp on the model which are maintained by us for developer
// convenience. Then we will just continue saving the model instances.
if ($this->timestamps && Arr::get($options, 'timestamps', true)) {
$this->updateTimestamps();
}
// [...]
타임 스탬프 필드는 public 속성 timestamps
이 같 true
거나 Arr::get($options, 'timestamps', true)
반환 true
되는 경우에만 업데이트됩니다 ( $options
배열에 key가 포함되지 않은 경우 기본적으로 수행됨 timestamps
).
즉시이 두 수익률 중 하나 false
의 timestamps
필드는 업데이트되지 않습니다.
Antonio Carlos Ribeiro의 답변에 추가하려면
코드에서 50 % 이상 타임 스탬프 비활성화가 필요한 경우 자동 업데이트를 비활성화하고 수동으로 액세스해야 할 수 있습니다.
웅변 모델을 확장 할 때 웅변 적으로 다음을 넣어 타임 스탬프를 비활성화 할 수 있습니다.
최신 정보
public $timestamps = false;
모델 내부.
위의 샘플은 멋지게 작동하지만 단일 개체에만 적용됩니다 (한 번에 한 행만).
전체 컬렉션을 업데이트하려는 경우 타임 스탬프를 일시적으로 비활성화하는 쉬운 방법입니다.
class Order extends Model
{
....
public function scopeWithoutTimestamps()
{
$this->timestamps = false;
return $this;
}
}
이제 다음과 같이 간단히 호출 할 수 있습니다.
Order::withoutTimestamps()->leftJoin('customer_products','customer_products.order_id','=','orders.order_id')->update(array('orders.customer_product_id' => \DB::raw('customer_products.id')));
For Laravel 5.x users who are trying to perform a Model::update()
call, to make it work you can use
Model::where('example', $data)
->update([
'firstValue' => $newValue,
'updatedAt' => \DB::raw('updatedAt')
]);
As the Model::update function does not take a second argument anymore. ref: laravel 5.0 api
Tested and working on version 5.2.
If you need to update single model queries:
$product->timestamps = false;
$product->save();
or
$product->save(['timestamps' => false]);
If you need to update multiple model queries use
DB::table('products')->...->update(...)
instead of
Product::...->update(...)
I ran into the situation of needing to do a mass update that involves a join, so updated_at
was causing duplicate column conflicts. I fixed it with this code without needing a scope:
$query->where(function (\Illuminate\Database\Eloquent\Builder $query) {
$query->getModel()->timestamps = false;
})
You can also use this syntax:
Model::where('Y', 'X')
->update(['Y' => 'Z'], ['timestamps' => false]);
I solved it my way, without playing with any configs (not the best way but helpful) :
$time = $user->updated_at; //write a copy of "updated_at" to $time variable
//do anything you want and let timestamp work as normal
$user->update('updated_at'=> $time) //At the end, rewrite the $time to "updated_at"
Don't forget to make updated_at
fillable
in your model.
ReferenceURL : https://stackoverflow.com/questions/18904853/update-without-touching-timestamps-laravel
'program tip' 카테고리의 다른 글
Spring Boot에서 @Repository 주석이 달린 인터페이스를 Autowire 할 수 없습니다. (0) | 2021.01.09 |
---|---|
모든 문자열에서 마지막 세 문자 가져 오기-Java (0) | 2021.01.09 |
Sublimetext 3을 git commit 텍스트 편집기로 설정 (0) | 2021.01.09 |
이 알고리즘의 Big-O 복잡성이 O (n ^ 2) 인 이유는 무엇입니까? (0) | 2021.01.09 |
종결되지 않은 문자열 리터럴의 일반적인 소스 (0) | 2021.01.09 |