cakehp3.0中的可控制行为不适用于多级关联



我在cakehp2.x工作了大约1.5年,这很好,现在我已经将自己转移到了Cakephp3.x,但我在获取具有多级关联的数据时遇到了问题。请通知我,我正在写数据。现在我的问题是!!在cakehp2.x中:我在像这样的控制器中使用了多级关联

CommentsController中:型号:发布型号:注释

帖子有许多评论(我在模型中定义的关系)评论属于帖子

$this->Post->Comment->find('all');

这个查询也返回了评论和它们的相关帖子,但现在在cakehp3.x中

$this->Posts->Comments->find();

它只返回了评论,但没有相关的帖子,但当我使用像这样的可控制行为时

$this->Post->Comments->find('all',['contain'=>['Posts'] ] )

这一次它显示错误帖子与评论无关现在我想知道我错了吗?

Cake 3中的表(模型)是复数。听起来你想做这样的事情:

$this->Posts->find()->contain(['Comments']);
// or
$this->Posts->find('all', ['contain' => ['Comments']]);

如果仍然出现错误,请确保已设置关联。

// src/Model/Table/PostsTable.php
public function initialize(array $config)
{
    parent::initialize($config);
    $this->hasMany('Comments');
}

也试试这个,我认为这会对有所帮助

$this->Posts->find('all')->contain(['Comments']);

cakehp3.x中尝试此操作

$this->Posts->Comments->find()->contain(['Posts'])->all();

$this->Posts->Comments->find()->contain(['Posts'])->toArray();

在尝试之前,请确保您的模型关系hasMany和belongsTo必须正确。

最新更新