您好我有一个PostgreSQL查询,我想用cakePHP格式编写
SELECT
id,
title,
author,
postdate,
postcontent,
userID
FROM posts
WHERE
userID = 12
AND id IN (SELECT articleID FROM favourites WHERE articlesUserID = 12)
ORDER BY postdate DESC;
这是我的查询现在在cakePHP中的格式:
$favouritearticles = $this->Favourite->query('SELECT id, title, author, postdate, postdatecreation, posteditdate, postcontent, "userID" FROM posts WHERE "userID" = '.$userID.'AND id IN (SELECT lngblogarticleid FROM favourites WHERE lngloginuserid = '.$userID.') ORDER BY postdate DESC');
它正在工作,但如果回显json_encode结果如下:
echo json_encode($favouritearticles);
我得到一个无效的json格式,如下所示:(使用JSONLint检查)
[
[
{
"id": 2,
"title": "Prison Or Treatment For the Mentally ill ",
"author": "mike123",
"postdate": "March 12, 2013 at 6:46 pm",
"postdatecreation": "2013-03-12",
"posteditdate": null,
"postcontent": "<p><span>The public revulsion over repeated mass shootings has placed mental health in the spotlight. This is both good and bad.<\/span><\/p>",
"userID": 34
}
]
][
]
所以我想也许我应该使用cakePHP格式“使用find方法”重写我的查询,例如:
$favouritearticles = $this->Favourite->find('all',array('conditions'=>array(".........
然而查询非常复杂,我不知道如何这样做。 谢谢你的帮助。
答案 0 :(得分:1)
JSON的格式很好,除了最后的额外[]。 如果您仍想以CakePHP格式重写查询,请使用以下命令:
private function getFavouritePostsByUserId($userId) {
$db = $this->Post->getDataSource();
$subQuery = $db->buildStatement(
array(
'fields' => array('Favourite.articleID'),
'table' => $db->fullTableName($this->Favourite),
'alias' => 'Favourite',
'conditions' => array(
'Favourite.articlesUserID' => $userId
),
),
$this->Favourite
);
$subQuery = 'Post.id IN (' . $subQuery . ') ';
$subQueryExpression = $db->expression($subQuery);
$conditions = array($subQueryExpression, 'Post.userID' => $userId);
$fields = array('Post.*');
$order = 'Post.postdate DESC';
$this->Post->find('all', compact('conditions', 'fields', 'order'));
}