我的CakePHP应用程序中有3个博客表,它们遵循CakePHP命名约定与HABTM关联链接:posts - post_tag_links - tags。
我尝试获取一个包含链接到特定标记的所有帖子的数组(例如" design")。此查询适用于我:
$this->Post->query("
SELECT
Post.id, Post.title FROM posts AS Post
LEFT JOIN
post_tag_links AS PostTagLink ON Post.id = PostTagLink.post_id
LEFT JOIN
tags AS Tag ON Tag.id = PostTagLink.tag_id
WHERE
Tag.slug = 'design'
GROUP BY
Post.id"
);
CakePHP然后生成以下查询并给我4个结果:
SELECT
Post.id,
Post.title
FROM
posts AS Post
LEFT JOIN
post_tag_links AS PostTagLink
ON Post.id = PostTagLink.post_id
LEFT JOIN
tags AS Tag
ON Tag.id = PostTagLink.tag_id
WHERE
Tag.slug = 'design'
GROUP BY
Post.id
但是......要做一些最佳实践,不要使用"查询"方法。所以我尝试了#34;找到所有"方法:
$this->Post->find('all', array(
'fields' => array(
'Post.id',
'Post.title'
),
'joins' => array(
array(
'table' => 'post_tag_links',
'alias' => 'PostTagLink',
'type' => 'LEFT',
'conditions' => array(
'Post.id' => 'PostTagLink.post_id'
)
),
array(
'table' => 'tags',
'alias' => 'Tag',
'type' => 'LEFT',
'conditions' => array(
'Tag.id' => 'PostTagLink.tag_id',
)
)
),
'conditions' => array(
'Tag.slug' => 'design'
),
'group' => 'Post.id'
)
));
CakePHP然后生成以下查询并且没有给出单个结果:
SELECT
`Post`.`id`,
`Post`.`title`
FROM
`kattenbelletjes`.`posts` AS `Post`
LEFT JOIN
`kattenbelletjes`.`post_tag_links` AS `PostTagLink`
ON (
`Post`.`id` = 'PostTagLink.post_id'
)
LEFT JOIN
`kattenbelletjes`.`tags` AS `Tag`
ON (
`Tag`.`id` = 'PostTagLink.tag_id'
)
WHERE
`Tag`.`slug` = 'design'
GROUP BY
`Post`.`id
经过大量的反复试验后,我发现问题是CakePHP在构建最后一个查询时创建的反引号。
我的问题是:查询与反引号和没有反引号的查询之间的区别是什么?你怎么能在CakePHP中留下这些反对意见?
谢谢;)
答案 0 :(得分:3)
反引号很可能不是问题所在,因为他们只是逃避标识符。这很容易找到顺便说一句。
实际问题更可能是你以错误的方式定义了条件,你正在做的是创建字符串文字比较条件,即
`Post`.`id` = 'PostTagLink.post_id'
将id
列值与字符串PostTagLink.post_id
进行比较当然会失败。
定义标识符比较的正确方法是将条件片段作为单个值而不是key =>提供。价值集,即
'conditions' => array(
'Post.id = PostTagLink.post_id'
)
和
'conditions' => array(
'Tag.id = PostTagLink.tag_id'
)
另见