Duc Anh
Duc Anh

Reputation: 581

Update rows in CakePHP

Im trying to update a row in cakePHP 2.3.1.I have class Test extend AppModel with $validates array, and the Controller( simplified ) :

public function editstudent()   {
    if($this->request->data)    {
        $this->Test->stuId= $this->data['Test']['stuId'];
        if ($this->Test->save($this->request->data))    {
            $this->set('state',1);
        }
    }

The book said that :

Creating or updating is controlled by the model’s id field. If $Model->id is set, the record with this primary key is updated. Otherwise a new record is created:

As above I've set $this->Test->StuId but when I submit form it still shows :

Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'PRIMARY' SQL Query: INSERT INTO ........

As the error showed,the query still is INSERT not UPDATE So what do I have to do to update,pls help me out :(

EDIT : @thaJeztah I've edit my view like this :

class Test extends AppModel {
var $name= 'Test';
var $primaryKey= 'stuId';
public $validate= array(.......);
}

But it still show the same problem

Database Error Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'PRIMARY' SQL Query: INSERT INTO cakePhp.tests (stuName, stuDoB, stuAdd) VALUES ('Đào Đức Anh', '2013-03-25', 'Kim Liên')

As you see the query is still INSERT not UPDATE,can you help me why this still happens :(

Upvotes: 0

Views: 2514

Answers (1)

thaJeztah
thaJeztah

Reputation: 28987

Because you're not following CakePHP conventions (see CakePHP Model Conventions, you will need to manually specify the primary-key and/or database-table to use for the Model;

class Test extends AppModel {
    public $primaryKey = 'studId';
}

Also, I wonder if 'Test' is a reserved name and may not be a proper name for the Model at all.

However, if this is a new project, I would strongly recommend to stick to the CakePHP conventions, they are there for a reason and will make life a lot easier when developing with this framework

update Removed the $useTable property based on comment by the OP

Upvotes: 2

Related Questions