2013-03-24 4 views
0

안녕하세요 나는이 내 쿼리가 CakePHP는 바로 지금이 형식입니다SQL 쿼리

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의 형식을 사용하여 쓰고 싶은 PostgreSQL의 쿼리가 :

$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을 얻을 다음과 같은 형식 :

[ 
    [ 
     { 
      "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의 형식을 사용하여 같은 것을 내 쿼리를 다시 작성해야한다고 생각 (JSONLint로 확인) :

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

쿼리는 매우이다 그러나 복잡하고 그렇게하는 법을 모르겠습니다. 도움 주셔서 감사합니다.

+0

무엇을 시도 했습니까? 이미 시도한 것을 보여주고 붙어있는 곳을 설명하십시오. –

+0

나는 내 질문에 약간의 변경을했다. – OussamaLord

답변

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 절 항목이 누락되었습니다. ")"posts "AS Post.id IN (SELECT Favorite .... ^) 단순히 반환 된 json에서 (또는 json_encoded()에 의해 전송되기 전에) 여분의 [[]을 어떻게 제거 할 수 있습니까? – OussamaLord

+0

'table'=> $ db-> fullTableName ($ this-> Favorite), '테이블'=> '즐겨 찾기', – Karisters

+0

안녕하세요, 같은 문제는 무엇에 관해서는 그 여분의 [] 제거? 감사 – OussamaLord