panthro
panthro

Reputation: 24061

Updating updated_at timestamp?

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?

Upvotes: 1

Views: 1562

Answers (2)

pinkal vansia
pinkal vansia

Reputation: 10310

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();
});

Upvotes: 0

Nicklas Kevin Frank
Nicklas Kevin Frank

Reputation: 6337

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');
    }

}

Upvotes: 3

Related Questions