Hanzo Miyagi
Hanzo Miyagi

Reputation: 21

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

Hi guys wondering if you can help figure out what this eloquent statement should look like. It's pretty challenging, at least for me, but maybe not for some of you guys? Here is the scenario:

I have a pivot table with post_id and user_id and an additional column called total_views in the pivot table.

Basically what I'm trying to do is increment the views each time the user goes and view that specific post.

This is what the SQL would look like:

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

How would you write this in an eloquent statement? Big thanks for the first that can come up with a solution!

Upvotes: 1

Views: 1630

Answers (2)

Hanzo Miyagi
Hanzo Miyagi

Reputation: 21

 \DB::table('post_user')->where(['u‌​ser_id'=>$user->id, 'post_id'=>$post->id])->increment('total_views');

This worked for me.

Upvotes: 1

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12391

DB::table('post_user')->increment('total_views'); and add some where clauses that's with query builder.

In eloquent, fetch the object, update the values and save.

$object = ModelName::find(1); ///use where clauses to get the record
$object->your_preferredColumn = $VALUE; //increment it here
$object->save(); //save the object

Upvotes: 1

Related Questions