CakePHP 可包含的错误:两级关联不起作用
-
12-12-2019 - |
题
我执行下一个查询:
$this->find('all',array(
'contain' => array(
'User' => array('id','facebook_id','name','username','Author' => array('first_name','last_name','code','photo')),
'Tab.code'
),
'fields' => array('Comment.date','Comment.time','Comment.content'),
'conditions' => array(
'Tab.code' => $code
),
'limit' => $limit,
'offset' => $offset
));
评论...
public $belongsTo = array(
'User' => array('foreignKey' => 'user_id'),
'Tab' => array('foreignKey' => 'tab_id')
);
用户...
public $hasOne = array('Author' => array('foreignKey' => 'id'));
和作者...
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'id'
)
);
这会返回类似这样的内容(以 json 格式)...
[
{
"Comment": {
"date": "2001-12-15",
"time": "17:32:12",
"content": "..."
},
"User": {
"id": "29",
"facebook_id": "1234",
"name": "User 29",
"username": "user29"
},
"Tab": {
"code": "llibre-de-prova-29",
"id": "229"
}
}
...
]
...虽然我希望附加到用户的内容会出现一个带有我指定字段的作者。你知道为什么作者没有出现吗?我在代码上做了其他包含两级递归的操作,并且所有内容都按预期工作。
感谢您的帮助和关注!
解决方案
确保您的模型具有附加的可容纳行为。它应包括以下行:
$actsAs = array('Containable');
.
注意确保您并没有省略“行为”中的“S”,这是一个难以解决的常见错误。您还可以像这样,如下所示,也可以附上可容纳行为:
$this->YourModel->Behaviors->attach('Containable');
$this->YourModel->find('all', array('contain' => array(...)));
.
还要确保您输入“包含”作为数组密钥,而不是“包含”。
其他提示
您需要在“fields”键中指定字段。将其视为额外的 find()
称呼。
$this->find('all', array(
'contain' => array(
'User' => array(
'fields' => array('id','facebook_id','name','username'),
'Author' => array(
'fields' => array('first_name','last_name','code','photo')
),
'Tab.code'
),
),
'fields' => array('Comment.date','Comment.time','Comment.content'),
'conditions' => array(
'Tab.code' => $code
),
'limit' => $limit,
'offset' => $offset
));
$this->find('all',array(
'contain' => array(
'User' => array('id','facebook_id','name','username','Author' =>array( 'AuthorModelName'=>array('first_name','last_name','code','photo'))),
'Tab.code'
),
. 所有外键必须在您的字段中阵列
'fields' => array('Comment.date','Comment.time','Comment.content', 'Comment.user_id', ....)
. 不隶属于 StackOverflow