在cakephp3中更新/插入相关的表数据

xoefb8l8  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(318)

我对cakephp3很陌生。我要更新/插入关系表数据。我有 Articles 作为主表,以及 Comments 是一个相关表,其中 article_id 作为外键存储。
另外,因为我不想重复的评论 Article ,我已设置唯一密钥 comment_id_bodyComments table。
我是这样定义这段关系的。

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

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

这是我的密码。

$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);

这段代码的问题是它总是试图在 Comments 表,而不是更新现有的表。所以当我执行代码时,它会给出如下的错误。
完整性约束冲突:1062个重复条目
我认为上面的错误是由于表中的记录重复造成的,因为上面的代码总是试图插入新的记录,而表中存在具有相同数据的记录 Comments table。
我想更新一下 Comments 表记录,如果在 Comments 表,则在通过调用 $articlesTable->save($article); 方法。

exdqitrt

exdqitrt1#

你说' Comments 是一个相关表,其中articleid存储为外键的
但在你的 CommentsTable 你的班级:

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

首先,假设文章可以有很多评论,但单个评论只适用于一篇文章[正常模式],您应该更改您的评论 CommentsTable 使上一行成为:

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

其次,外键的格式不遵循cakephp约定,因此请更改 articleID 字段到 article_id -或者参考文档了解如何将参数添加到 belongsTo() 使用非常规外键。
如果仍然出现“重复条目”错误,则数据库中的注解表可能有问题(你让身体领域独一无二吗?)

相关问题