Laravel Pivot Table - 如何用计数器增加第三个字段?

Laravel Pivot Table - How to increment third field with counter?

大家好,想知道您是否可以帮助弄清楚这个 eloquent 语句应该是什么样子。这很有挑战性,至少对我来说是这样,但对你们中的一些人来说可能不是这样?这是场景:

我有一个主元 table,其中 post_id 和 user_id 以及主元 table 中的一个名为 total_views 的附加列。

基本上我想做的是在每次用户查看特定 post 时增加视图。

这就是 SQL 的样子:

UPDATE post_user SET total_views = total_views+1 WHERE user_id=1 AND post_id=2

你会如何在 eloquent 语句中写这个?非常感谢第一个能想出解决办法的!

DB::table('post_user')->increment('total_views'); 并添加一些带有 query builder 的 where 子句。

eloquent中,获取对象,更新值并保存。

$object = ModelName::find(1); ///use where clauses to get the record
$object->your_preferredColumn = $VALUE; //increment it here
$object->save(); //save the object
 \DB::table('post_user')->where(['u‌​ser_id'=>$user->id, 'post_id'=>$post->id])->increment('total_views');

这对我有用。