Ashok Gujjar
Ashok Gujjar

Reputation: 441

Update/Insert Associated Table data in CakePHP 3

I am very new to CakePHP 3. I want to Update/Insert relation table data. I have Articles as the s Main table, and Comments is a related table in which article_id is stored as the foreign key.

Also, As I don't want the duplicate comment for the Article, I have set up unique key comment_id_body In Comments table.

Here is how I defined the relationship.

class ArticlesTable extends Table
{
    public function initialize(array $config)
    {
        $this->hasMany('Comments');
    }
}

class CommentsTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsTo('Articles');
    }
}

Here is my code.

$articlesTable = TableRegistry::get('Articles');
$article = $articlesTable->get(12);

$article->title = 'CakePHP is THE best PHP framework!';

$firstComment = $articlesTable->Comments->newEntity();
$firstComment->body = 'The CakePHP features are outstanding';

$article->comments = [$firstComment];

$articlesTable->save($article);

The issue with this code is it always tries to Insert a new row into the Comments table instead of updating the existing one. So when I execute code it gives the error like below.

Integrity constraint violation: 1062 Duplicate entry

I think the error above is due to duplication of record in the table as the code above is trying to insert new record all times while we have record with same data is exist in the Comments table.

I want to Update Comments table record, and if no record found in Comments table then it will automatically INSERT new one while saving data by calling $articlesTable->save($article); method.

Upvotes: 2

Views: 684

Answers (1)

Annabel
Annabel

Reputation: 1414

You say 'Comments is a related table in which ArticleID is stored as the foreign key'

But in your CommentsTable class you have:

$this->belongsToMany('Articles');   // Means a Comment can belong to MULTIPLE Articles

Firstly, assuming that Articles can have many Comments but an individual Comment only applies to one Article [the normal pattern], you should change your CommentsTable class so that the above line becomes:

$this->belongsTo('Articles');  // now a Comment only belongs to ONE Article

Secondly, the format of your foreign key does not follow CakePhp conventions so change the name of the articleID field to article_id - or consult the documentation for how to add parameters to the belongsTo() to use a non-conventional foreign key.

If you still get the 'Duplicate entry' error there might be a problem with your comments table in the database. (Did you make the body field unique?)

Upvotes: 0

Related Questions