現在我使用下面的代碼從某些類別買書:如何讓本本
$options['conditions']['Category.id'] = $category_id;
$options['joins'] = array(
array(
'table' => 'books_categories',
'alias' => 'BookCategory',
'type' => 'inner',
'conditions' => array('Book.id = BookCategory.id_book'),
),
array(
'table' => 'categories',
'alias' => 'Category',
'type' => 'inner',
'conditions' => array('BookCategory.kat = Category.id'),
),
);
$this->Book->find('all',$options);
這只是發現從給定的CATEGORY_ID所有圖書。
所以有3個表格:categories
,books
和books_categories
。 books_categories有兩個檔案:book_id
和category_id
所以基本上它只是HABTM關係。問題是,一本書可能屬於很多類別,我想要例如查找所有5類書籍,但不包括5,6和7類書籍。我該如何做?
編輯--------------------------------------------- ----------------------------------
好吧,我想出了它應該如何看待純SQL - 條件應該是這樣的:
where
category_id = <given category>
and books.book_id not in
(
select book_id from book_categories
where category_id in (<given set of cat>)
)
order by books.inserted
這將讓所有的書從一個範疇,而是從一組其他類別的圖書除外。 現在我想強制Cake生成類似的SQL查詢。 我試過到目前爲止:
$options['conditions']['Category.id'] = $category_id;
$options['conditions']['AND'][] = 'Book.id NOT IN (SELECT id_book FROM book_categories WHERE kat IN (133,134))';
$options['order'] = array('Book.inserted' => 'desc');
$options['joins'] = array(
array(
'table' => 'book_categories',
'alias' => 'BookCategory',
'type' => 'inner',
'conditions' => array('Book.id = BookCategory.id_book'),
),
array(
'table' => 'categories',
'alias' => 'Category',
'type' => 'inner',
'conditions' => array('BookCategory.kat = Category.id'),
),
);
這會產生這個查詢(索裏 - 表名是有點不同):
SELECT `Book`.`id`, `Book`.`OK`, `Book`.`price`, `Book`.`link`, `Book`.`title`,
`Book`.`author`, `Book`.`img`, `Book`.`inserted`, `Book`.`checked`, `Book`.`big_img`, `Book`.`lang`, `Book`.`asin`, `Book`.`description`, `Book`.`last_update`, `Book`.`review`, `Book`.`changed`
FROM `amazon`.`linki` AS `Book`
inner JOIN `amazon`.`cross_kategorie_full` AS `BookCategory` ON (`Book`.`id` = `BookCategory`.`id_book`)
inner JOIN `amazon`.`kategorie` AS `Category` ON (`BookCategory`.`kat` = `Category`.`id`)
WHERE `Category`.`id` = 4
AND `Book`.`OK` = 'OK'
AND ((`Book`.`big_img` NOT LIKE '%no-image%')
AND (`Book`.`id` NOT IN (SELECT id_book FROM cross_kategorie_full WHERE kat IN (133,134))))
ORDER BY `Book`.`inserted` desc LIMIT 20
但有錯誤:30秒最大的執行時間超過了 - 所以有是不結束在此SQL語句(循環?)什麼......
你必須使用mysql命令來運行此查詢從殼。超時是因爲你通過php腳本運行它(我是否正確?)... – Oerd
現在,這個查詢優化問題是另一個問題:)你知道你正在運行'NOT IN(SELECT id_book FROM。每個單獨的記錄都是?'(正如我微妙地提示我的答案)。這是另一個加入我的朋友! – Oerd