我有一個CakePHP查找條件的問題。我有一個俱樂部的模式,用戶模式和Post模型:CakePHP - 查找條件與協會
俱樂部的hasMany後
俱樂部HABTM用戶
基本上,我clubs_users表還包含其他字段,如讓我們說「限制」和' diff'分別表示用戶想要顯示的帖子的最大數量以及這些帖子被允許的多大。我想爲與給定用戶相關的每個俱樂部選擇適當的帖子。我正在做這樣的事
$clubs = $this->Club->User->find('first', array(
'conditions' => array('User.id' => $id),
'contain' => array(
'Club' => array(
'fields' => array(
'id',
'name'
),
'Post' => array(
'fields' => array(
'id',
'title',
'description',
'created',
),
'order' => array('Post.created' => 'DESC'),
'conditions' => array(
'DATEDIFF(NOW(), `Post.created`) <= /* 1 */',
),
'limit' => '/* 2 */'
)
)
)
));
我應該把這個工作而不是1和2放在什麼?我試過ClubsUser.diff和ClubsUser.limit,但是我得到一個錯誤,說明那些字段在where子句中是未知的。
任何幫助將受到歡迎。
感謝您的閱讀。
編輯
bancer的評論後,我看了看深入到MySQL的doc和它似乎LIMIT僅期望數值參數。所以我現在只想返回不太舊的帖子。我的新發現是(與實際字段名稱)
$overview = $this->Club->Follower->find('first', array(
'conditions' => array('Follower.id' => $this->Auth->user('id')),
'contain' => array(
'Club' => array(
'fields' => array(
'id',
'name'
),
'Post' => array(
'fields' => array(
'id',
'title',
'description',
'created',
),
'order' => array('Post.created' => 'DESC'),
'conditions' => array(
'DATEDIFF(NOW(), `Post.created`) <= ClubsUser.max_time_posts',
),
'limit' => 10
)
)
)
));
它會產生以下三個SQL查詢(我換成*爲清楚起見命名字段):
SELECT * FROM `users` AS `Follower`
WHERE `Follower`.`id` = 1
LIMIT 1
SELECT * FROM `clubs` AS `Club`
JOIN `clubs_users` AS `ClubsUser`
ON (`ClubsUser`.`user_id` = 1 AND `ClubsUser`.`club_id` = `Club`.`id`)
ORDER BY `ClubsUser`.`role_id` DESC
SELECT * FROM `posts` AS `Post`
WHERE DATEDIFF(NOW(), `Post`.`created`) <= `ClubsUser`.`max_time_posts` AND `Post`.`club_id` = (1)
ORDER BY `Post`.`created` DESC
LIMIT 10
最後的查詢返回錯誤:場「ClubsUser.max_time_posts」未知在where子句
理想的情況下,我想獲得一個查詢接近一個下方,而不是上方的最後兩個查詢:
SELECT * FROM `clubs` AS `Club`
JOIN `clubs_users` AS `ClubsUser`
ON (`ClubsUser`.`user_id` = 1 AND `ClubsUser`.`club_id` = `Club`.`id`)
LEFT JOIN `posts` AS `Post`
ON (`Post`.`club_id` = `Club`.`id` AND DATEDIFF(NOW(), `Post`.`created`) <= `ClubsUser`.`max_time_posts`)
ORDER BY `ClubsUser`.`role_id` DESC, `Post`.`created` DESC
LIMIT 10
任何想法?
是由你的代碼產生什麼SQL查詢?從調試輸出複製粘貼。需要什麼SQL查詢? – bancer 2012-01-13 01:07:56
@bancer:我編輯了我的問題 – 2012-01-14 12:47:07