2013-03-24 57 views
0

你好,我有一個PostgreSQL的查詢,我想使用CakePHP格式SQL查詢CakePHP的格式(無效的JSON結果)

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

您試過了什麼?請顯示你已經嘗試過的內容,並解釋你卡在哪裏。 – 2013-03-24 04:45:59

+0

我對我的問題做了一些修改,謝謝。 – OussamaLord 2013-03-24 10:45:05

回答

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')); 
} 
+0

你好,謝謝你的答案,我試過你的查詢格式,但它給了我一個錯誤:錯誤:SQLSTATE [42P01]:未定義的表:7錯誤:缺少表「最喜歡」的FROM-clause條目LINE 1:... lic 「。」posts「AS」Post「WHERE Post.id IN(SELECT Favorite .... ^我怎樣才能從返回的json中簡單地刪除額外的[],或者在它被json_encoded()發送之前。 – OussamaLord 2013-03-24 14:29:26

+0

替換爲 'table'=> $ db-> fullTableName($ this-> Favorite), 您的收藏夾名稱如下: 'table'=>'favorites', – Karisters 2013-03-24 14:49:02

+0

嗨,同樣的問題,那麼刪除那些額外的[]?謝謝 – OussamaLord 2013-03-24 15:20:48