0

您好,我有一个 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');

它正在工作,但如果 echo 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 格式“使用查找方法”重写我的查询,例如:

$favouritearticles = $this->Favourite->find('all',array('conditions'=>array(".........

但是查询非常复杂,我不知道该怎么做。感谢您的任何帮助。

4

1 回答 1

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'));
}
于 2013-03-24T13:51:37.227 回答