php - 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 查询:选择
CommentsGroup
。id
,CommentsGroup
.name
从botobot_comments
。在comment_groups
哪里。= 。CommentsGroup
CommentsGroup
id
CommentsSubGroup
group_id
有什么猜测吗?或者我错了,我应该使用 $hasMany 关系?
谢谢。
解决方案
您使用 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
推荐阅读
- wpf - WPF - 确定动态创建的控件是否适合容器
- java - 在 Adf 中撤消编辑后如何保留当前行的值?
- c# - UWP 中的 USB 设备通信
- swift - IOS交换机具体圆形边框
- spss - 如何在宏定义中使用数据值
- java - 为什么需要单独安装 Apache Hadoop 才能运行 Apache Spark...?
- angular - 如何打开 localhost 以外的 Angular 应用程序?
- outlook-addin - 在 Outlook for Mac 与 OWA 中呈现组合电子邮件的方式之间的差异
- android - ReactPropGroup 的示例
- google-assistant-sdk - google-library 1.0.1 更新后的分段错误