我对 cakePHP 查找条件有疑问。我有一个 Club 模型、一个 User 模型和一个 Post 模型:
俱乐部有很多帖子
俱乐部 HABTM 用户
基本上,我的 clubs_users 表还包含附加字段,例如“限制”和“差异”,它们分别表示用户想要显示的最大帖子数以及允许这些帖子的年龄。我想为与给定用户相关的每个俱乐部选择合适的帖子。我正在做这样的事情
$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 文档,看起来 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
最后一个查询返回错误:where 子句中的字段“ClubsUser.max_time_posts”未知
理想情况下,我希望得到一个接近下面的查询,而不是上面的最后两个查询:
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
有任何想法吗 ?