【问题标题】:Cakephp 3 - limit () and contained modelCakephp 3 - limit() 和包含模型
【发布时间】:2016-11-23 09:51:46
【问题描述】:

我有两个模型,名为 Post 和 Comment,它们通过 Post hasMany Comment 和 Comment belongsTo Post 链接。 我想获取前五个 cmets 的所有帖子。我会使用这段代码:

$this->Posts->find('all')
     ->contain([
        'Comments' => function($q) {
            return $q
                ->order('created ASC')
                ->limit(5);
}
]);

这与 limit() 一起工作不正确。请帮助解决这个问题。 我用了这个例子: How to limit contained associations per record/group? 我试图喜欢这个(在 Post 模型中):

$this->hasOne('TopComments', [
    'className' => 'Comments',
    'strategy' => 'select',
    'conditions' => function (\Cake\Database\Expression\QueryExpression $exp, \Cake\ORM\Query $query) {
        $query->leftJoin(
            ['CommentsFilter' => 'comments'],
            [
                'TopComments.post_id = CommentsFilter.post_id',
                'TopComments.created < CommentsFilter.created'
            ]);
        return $exp->add(['CommentsFilter.id IS NULL']);
    }
]);

在后期控制器中:

$this->Posts->find('all')
     ->contain([
        'TopComments' => function($q) {
            return $q
                ->order('TopComments.created ASC')
                ->limit(5);
}
]);

不幸的是,这不起作用。我不知道我哪里错了。

【问题讨论】:

标签: cakephp find cakephp-3.0 limits contain


【解决方案1】:

你应该试试这个

在你的模型中

$this->hasMany('Comments', [
    'foreignKey' => 'post_id'
]);

在你的控制器中

$this->Posts->find()
     ->contain([
        'Comments' => function($q) {
            return $q
                ->order(['created' =>'ASC'])
                ->limit(5);
}
]);

【讨论】:

  • 不幸的是它不起作用。 CakePHP 是一个强大的框架,但有时会发生基本的事情不能正常工作。
  • 是的,它在 cakephp 3 中不起作用,在包含条件中使用限制
猜你喜欢
  • 2016-11-07
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多