1

我有以下搜索查询(需要有年/月和帖子的标签,以便在添加评论后进行正确的重定向)。

$settingsForPostQuery = array(
            'fields' => array(
                'Post.slug',
                'YEAR(Post.date_published) as year',
                'MONTH(Post.date_published) as month'
            ),
            'conditions' => array('Post.id' => $this -> request -> params['post_id'])
        );
// unbind post model to fetch only necessary stuff
$this -> Comment -> Post -> unbindModel(array(
            'hasMany' => array('Comment'),
            'hasAndBelongsToMany' => array('Tag'),
            'belongsTo' => array('Category')
));

$post = $this -> Comment -> Post -> find('published', $settingsForPostQuery);

这就是我得到的Debugger::dump($post);

array(
(int) 0 => array(
    'Post' => array(
        'slug' => 'this-is-a-second-test-post-in-the-category-internet'
    ),
    (int) 0 => array(
        'year' => '2012',
        'month' => '6'
    )
)
)

不是更合乎逻辑吗:

array(
(int) 0 => array(
    'Post' => array(
        'slug' => 'this-is-a-second-test-post-in-the-category-internet',
        'year' => '2012',
        'month' => '6'
     )      
  )
)

如果您需要信息,“已发布”是自定义查找类型,定义如下:

protected function _findPublished($state, $query, $results = array()) {
    if ($state === 'before') {
        $query['conditions']['Post.is_archived'] = false;
        $query['conditions'][] = 'Post.date_published <= now()';
        return $query;
    }
    return $results;
}

编辑

我发现当只使用 Post.date_published 而不是 YEAR(Post.date_published) 时,Post.date_published 也会出现在 Post 数组中,就像 slug 一样。为什么使用 MYSQL 函数会改变这一点?

4

1 回答 1

4

当您在查询中添加字段时,CakePHP 中会发生这种情况,我相信您可以使用正确的别名命名约定使它们成为主数据数组的一部分MyModel__MyField

$settingsForPostQuery = array(
        'fields' => array(
            'Post.slug',
            'YEAR(Post.date_published) as Post__year',
            'MONTH(Post.date_published) as Post__month'
        ),
        'conditions' => array('Post.id' => $this -> request -> params['post_id'])
    );

在这里阅读更多。顺便说一句,您应该查看可包含以限制查询的模型而不是取消绑定它们:)

于 2012-07-05T08:42:45.990 回答