首页 > 解决方案 > CakePhp 2.5 $belongsTo 两种型号

问题描述

现在我有这个: Groups Inside Groups we have Subgroups Inside Subgroups we have Comments

子组属于第 1、2、3 组;subgroups 表有group_id字段 Comments 属于子组 A、B、C ;评论表有subgroup_id字段

我的模型:

评论组.php

<?php

App::uses('AppModel', 'Model');

class CommentsGroup extends AppModel {

    public $useTable = 'comment_groups';

}

CommentsSubGroup.php

<?php

App::uses('AppModel', 'Model');

class CommentsSubGroup extends AppModel {

    public $useTable = 'comment_subgroups';

    public $belongsTo = array(
        'CommentsGroup' => array(
            'className'  => 'CommentsGroup',
            'foreignKey' => false,
            'conditions' => ['`CommentsGroup`.`id` = `CommentsSubGroup`.`group_id`']
        )
    );

}

评论.php

<?php

App::uses('AppModel', 'Model');

class Comment extends AppModel {

    public $belongsTo = array(
        'CommentsSubGroup' => array(
            'className' => 'CommentsSubGroup',
            'foreignKey' => false,
            'conditions' => ['`CommentsSubGroup`.`id` = `Comment`.`subgroup_id`']
        )
    );

}

当我尝试从我的控制器获取与评论相关的 subgroup_id 时,没关系。当我尝试获取更多(链接到 subgroup_id 的 group_id)时,我失败了。

没有递归的查询是可以的,否则我有:

$data = $this->_Model->find('all', ['conditions' => ['subgroup_id' => $id], 'recursive' => 2, 'order' => [$this->_Modelname . '.id' => 'DESC']]);

考虑到$this->_Model等于Comment

我遇到的错误:

数据库错误错误:SQLSTATE [42S22]:找不到列:1054 'where 子句'中的未知列 'CommentsSubGroup.group_id'

SQL 查询:选择CommentsGroupid, CommentsGroup. namebotobot_comments。在 comment_groups哪里。= 。CommentsGroupCommentsGroupidCommentsSubGroupgroup_id

有什么猜测吗?或者我错了,我应该使用 $hasMany 关系?

谢谢。

标签: phpmysqlcakephpcakephp-2.5

解决方案


您使用 belongsTo 关系是正确的,但您需要指定foreignKey属性才能使关系起作用。您还需要从conditions键中取出连接条件(因为 Cake 可以根据外键计算出来)。

例如:

App::uses('AppModel', 'Model');

class Comment extends AppModel {

    public $belongsTo = array(
        'CommentsSubGroup' => array(
            'className' => 'CommentsSubGroup',
            'foreignKey' => 'subgroup_id'
        )
    );

}

您还需要对模型和表遵循 Cakes 命名约定,否则您需要在各自的模型中显式声明表名和主键。

在您的情况下,CommentsSubGroup应该CommentSubGroup假设名为 comment_sub_group 的表和主键为 comment_sub_group_id


推荐阅读