[英]Insert and update count in MySQL Eloquent
我有一張這樣的桌子:
User (user_id, count)
現在我想在此表中插入一個用戶ID,然后更新count = count +1。我該如何雄辯地做到這一點?
我試過了:
protected $table = 'user';
public function insertAndUpdateCount($user_id)
{
return $this->insert($user_id)
->increment('count', 1);
}
但這似乎不起作用。
您是否嘗試過使用增量和減量?
https://laravel.com/docs/5.8/queries#increment-and-decrement
像這樣
DB::table('users')->increment('votes', 5);
我建議您將count
列設置為autoincrement
。 因此,每次插入新行時,該值都會自動增加1。您可以在Laravel遷移中執行以下操作: $table->integer('count', true)
table- $table->integer('count', true)
在此處了解有關Laravel遷移的更多信息: https:/ /laravel.com/docs/5.8/migrations
出於好奇:為什么首先需要count
列? 如果只是某個時候要獲取行數,那么此時最好使用SELECT COUNT()
。 因為使用專用的count
列,不僅浪費內存,而且還容易出錯,因為如果刪除一行,其他行的count
數值將不會更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.