Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
CakePhp 2.5$belongsTo分为两种型号_Php_Mysql_Cakephp_Cakephp 2.5 - Fatal编程技术网

CakePhp 2.5$belongsTo分为两种型号

CakePhp 2.5$belongsTo分为两种型号,php,mysql,cakephp,cakephp-2.5,Php,Mysql,Cakephp,Cakephp 2.5,现在我有这个: 组 在组内我们有子组 在小组内部,我们有意见 子组属于组1、2、3;子组表具有组id字段 评论属于A、B、C分组;注释表具有子组id字段 我的模型: CommentsGroup.php <?php App::uses('AppModel', 'Model'); class CommentsGroup extends AppModel { public $useTable = 'comment_groups'; } 考虑到$this->\u模型等于注释 我的

现在我有这个: 组 在组内我们有子组 在小组内部,我们有意见

子组属于组1、2、3;子组表具有
组id
字段 评论属于A、B、C分组;注释表具有
子组id
字段

我的模型:

CommentsGroup.php

<?php

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

class CommentsGroup extends AppModel {

    public $useTable = 'comment_groups';

}
考虑到
$this->\u模型
等于
注释

我的错误是:

数据库错误:SQLSTATE[42S22]:未找到列:1054未知 “where子句”中的“CommentsSubGroup.group\u id”列

SQL查询:从中选择
CommentsGroup
id
CommentsGroup
name
botobot\u comments
comment\u groups
AS
comments group
WHERE
CommentsGroup
id
=
commentsSBGroup
group\u id

猜猜看?或者我错了,我应该使用$hasMany关系


谢谢。

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

例如:

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


在您的情况下,
CommentsSubGroup
应该是
CommentSubGroup
,它假定名为comment\u sub\u group的表和comment\u sub\u group\u id的主键仍然存在相同的错误。如果我们检查错误,查询将缺少一个别名和一个左连接。某处还缺少其他东西…:SIt可能是因为您的模型没有遵循正确的命名约定-请参阅我的更新回复。是的,因为我正在处理一个已经存在的db,所以我无法遵循良好的命名约定。顺便说一句,即使更新了代码,仍然会出现相同的错误。
<?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

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

class Comment extends AppModel {

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

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

class Comment extends AppModel {

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

}