我有以下搜索查询(需要有一个帖子的年/月和slug,以便在添加评论后进行正确的重定向)。
$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函数改变了这个?
答案 0 :(得分: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'])
);
Read more here。 顺便说一句,您应该查看containable以查询模型的限制,而不是解除绑定:)