使用由3列组成的复合主键保存hasMany关联数据

时间:2017-02-10 14:09:10

标签: php cakephp orm composite-key cakephp-3.3

我有两个表,即评论和评分。注释表具有主键['comment_id','source_id'],而评级表具有主键['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

     

Debug:duration = 1 rows = 0 SELECT 1 AS existing FROM comments as   评论WHERE(comments.comment_id = '12'和comments.source_id = 4)   限制1

     

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

     

调试:持续时间= 1行= 0选择1 AS existing FROM评级为   评级WHERE(ratings.comment_id = '12'和ratings.source_id = 4)   限制1

     

调试:持续时间= 1行= 1 INSERT INTO评级(comment_id,source_id,   topic_id,rating,created)VALUES('12',4,5,4,'2017-02-09   13时06分04' 秒)

     

调试:持续时间= 1行= 1选择1 AS existing FROM评级为   评级WHERE(ratings.comment_id = '12'和ratings.source_id = 4)   限制1

     

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

     

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

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

我已经在搜索过SO并搜索了它。找到的解决方案确实满足我的要求。我的情况不同,因为评级表有3列复合主键,其中3个前2个是评论表的外键。

0 个答案:

没有答案