pawelmysior
pawelmysior

Reputation: 3250

Save without updating the 'modified' field

I'm working on a new project using CakePHP 3.0.

I'm using the authentication component and whenever a user logs in, I'm updating the value of the field visited.

UsersController:

public function login() {

    if ($this->request->is('post')) {

        $user = $this->Auth->identify();

        if ($user) {

            $this->Auth->setUser($user);

            $this->Users->setVisited($user['id']);

            return $this->redirect($this->Auth->redirectUrl());

        }

    $this->Flash->error('Your username or password is incorrect.');

    }

}

UsersTable:

public function setVisited($id) {

    $user = $this->findById($id)->first();

    $user->visited = Time::now();

    if($this->save($user)) {

        return true;

    }

    return false;

}

Now, I would like to do this save without updating the value of the field modified. I've tried the approach used in previous versions of cake:

$user->modified = false;

It doesn't work though, throwing and error: Call to a member function format() on a non-object because datetime fields are now treated as objects I guess.

Any help would be greatly appreciated,

Paul

Upvotes: 2

Views: 1016

Answers (1)

You have a couple ways of doing this. What you want is actually to avoid calling callbacks when saving the entity. For those cases you have updateAll

$this->updateAll(['visited' => Time::now()], ['id' => $id]);

You can also do the same as before, but you will need to disable the Timestamp behavior before saving:

$this->behaviors()->unload('Timestamp');

I would recommend using updateAll

Upvotes: 3

Related Questions