2

How do I delete a record in CakePHP 2.x when I am using an auto increment primary key named users_id instead of id?

I am using the following code:

$this->User->delete(12);

But it is not working.

Inigo Flores
  • 4,461
  • 1
  • 15
  • 36
joy
  • 81
  • 1
  • 8

2 Answers2

4

You have to declare in your model the name of the field you will be using as primary key. For example:

class User extends AppModel {
    // user_id is the field name in the database
    public $primaryKey = 'user_id';
}

The following should now work:

$this->User->delete(12);

This syntax is also allowed:

$this->User->id = 12;
$this->User>delete();
Inigo Flores
  • 4,461
  • 1
  • 15
  • 36
0

With the deleteAll()method you can specifiy conditions like you would do in a query. So in your case it would be

$this->User->deleteAll(array('User.user_id' => 12));

refer to http://book.cakephp.org/2.0/en/models/deleting-data.html for more details

Max90
  • 193
  • 2
  • 14
  • Can you explain what is user , findByEmail and visitor in cakephp. $this->User->Visitor->findByEmail – joy Dec 19 '15 at 08:21
  • The cakephp `findBy()` functions that return the item specified in brackets, e.g. $this->User->VisitorfindByEmail('test@email.com'); returns a visitor with the email specified in brackets. It is just a short version for $this->User->Visitor->find('all', array('conditions' => array('Visitor.email' => 'test@email.com'))); see: http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#findby – Max90 Dec 20 '15 at 20:56