1

我有两张表,即评论和评级。Comments 表有主键['comment_id','source_id'],Ratings 表有主键['comment_id','source_id','topic_id']

模型关系定义如下:

    /* Model comments Table*/

    $this->table('comments');
    $this->primaryKey(['comment_id','source_id']);
    $this->hasMany('Ratings',[
        'foreignKey'=>['comment_id','source_id']
    ]);

    /* Model Ratings Table*/

    $this->table('ratings');
    $this->primaryKey(['comment_id','source_id','topic_id']); // Notice the primary key has 3 columns
    $this->belongsTo('Comments',[
        'foreignKey'=>['comment_id','source_id']
    ]);

我想插入多条评论,每条评论都会有多个与之相关的评分,每条评论下的不同评分属于不同的评分主题。我正在尝试使用 saveMany 语法保存评论及其相关评级,但是 cakePHP 正确保存评论但两个评级都没有保存,它只保存最后一个评级。

/* Inside controller's action */

    $comment['comment_id'] = '12';
    $comment['source_id'] = 4;
    $comment['travel_date'] = '';
    $comment['ratings'] = [
        [   //This doesn't gets saved
        'topic_id' =>5,
        'rating' =>4,
        'created' =>'2017-02-09 13:06:04'
        ],
        [   //This gets saved
        'topic_id' =>6,
        'rating' =>5,
        'created' =>'2017-02-09 13:06:04' 
        ]];

    $multipleRows[0] = $comment;
    $newRows = $this->Comments->newEntities($multipleRows,['associated' => ['Ratings']]);
    $this->Comments->saveMany($newRows);

我做了一个 SQL 日志,发现了这个:

调试:持续时间=0 行=0 BEGIN

调试:duration=1 rows=0 SELECT 1 AS existingFROM comments as comments WHERE (comments.comment_id = '12' AND comments.source_id = 4) LIMIT 1

调试:duration=1 rows=1 INSERT INTO comments (comment_id, source_id, travel_date) VALUES ('12', 4, '')

调试:duration=1 rows=0 SELECT 1 AS existingFROM rating as rating WHERE (ratings.comment_id = '12' AND rating.source_id = 4) LIMIT 1

调试:持续时间=1 行=1 插入评分(comment_id、source_id、topic_id、评分、创建)值('12'、4、5、4、'2017-02-09 13:06:04')

调试:duration=1 rows=1 SELECT 1 AS existingFROM rating as rating WHERE (ratings.comment_id = '12' AND rating.source_id = 4) LIMIT 1

调试:持续时间 = 1 行 = 1 更新评级 SET topic_id = 6 ,评级 = 5 ,创建 = '2017-02-09 13:06:04' WHERE(comment_id = '12' AND source_id = 4)

调试:持续时间=0 行=0 提交

如果您看到上面的日志,CakePHP 会检查是否有重复,并且如果记录已经存在,那么它会更新记录而不是添加新行。但是,这里的问题是,对于这个检查,CakePHP 只使用外键而不是目标表的主键。在我的情况下,主键包含 3 列,其中前 2 列构成外键。如何解决此问题并在这种情况下插入多重评分?

我已经在 SO 上搜索过,也用谷歌搜索过。找到的解决方案确实满足我的情况。我的情况不同,因为评级表有 3 列复合主键,而这 3 列中的前 2 列是评论表的外键。

4

0 回答 0