我沿着這個線路查詢:翻譯一個SELECT/IN的SQL查詢來發現蛋糕
SELECT * FROM posts WHERE owner_id IN (SELECT owner_id FROM owners_list WHERE user_id = 1) ORDER BY modified DESC
什麼是最有效的蛋糕找到調用等同?謝謝!
我沿着這個線路查詢:翻譯一個SELECT/IN的SQL查詢來發現蛋糕
SELECT * FROM posts WHERE owner_id IN (SELECT owner_id FROM owners_list WHERE user_id = 1) ORDER BY modified DESC
什麼是最有效的蛋糕找到調用等同?謝謝!
3個選擇:
1)蛋糕做處理子查詢,但它是複雜的: http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#sub-queries
這裏有一個SO問題必然有一個例子: Subquery in cakePHP to lookup in other table
2)使用加入聲明: http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#joining-tables
3)您可以使用您的查詢原樣通過Model::query()作爲只要你先清潔
我更喜歡選項2,因爲它不太容易出錯,我不必擔心消毒/轉義。而且一旦你掌握了聯結的經驗,你會發現自己更經常使用它們。
您可以通過兩種認定做到這一點。我將假設您的owners_list表的型號名稱是OwnersList:
$user_ids = $this->OwnersList->find('list', array(
'fields'=>array('id','id'),
'conditions'=>array(
'OwnersList.user_id'=>1
)
));
$results = $this->Post->find('all',array(
'Post.owner_id'=>$user_ids
));