1

I have a products table and a users table. I sync the many to many relationship using:

Product::find($id)->user()->sync([$myVar], false); 

How can I touch the timestamps on the users table so that the updated_at field updates?

2 Answers 2

3

I think what you actually want is to setup a touches array on your products.

If you add this: protected $touches = array('user'); into your products models, the parent (in this case user) timestamps will automatically get updated anytime you use sync().

Ex.

class Products extends Eloquent { protected $touches = array('user'); public function user() { return $this->belongsTo('User'); } } 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I've tried this - I get the error Call to a member function sync() on null
Here's my line: Product::find($id)->user()->touch()->sync([$myVar], false);
0

I presume that there is Many to Many relationship between Product and User as you are using sync method. I presume that $myVar is single user id, because sync aspects first variable to be array of ids of related model. And I presume that you only want to touch the User with id $myVar. Do following,

Product::find($id)->user()->sync([$myVar], false); User::find($myVar)->touch(); 

Following will update all the users associated with Product which is not right. Because you may have attached many users before and it is not correct to update old associated users.

Product::find($id)->user->each(function($user){ $user->touch(); }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.