[英]How do I order query results by an associated model field with conditions?
I've spent the last two days trying to find a solution to this problem so anyone that can either provide a solution or a link to somewhere I could find out what I need to know would be doing me a huge favour. 我花了最后两天的时间来寻找解决此问题的方法,以便任何可以提供解决方案或链接到某个我可以确定自己所需要知道的内容的人都将为我提供极大的帮助。
I've got the following model relationships in CakePHP 我在CakePHP中具有以下模型关系
Keyword hasMany Click
I want to construct a query (either through $this->Keyword->find or by using a custom query) that will return a list of similar keywords ordered by the number of clicks they've received in the last week. 我想构造一个查询(通过$ this-> Keyword-> find或使用自定义查询),该查询将返回一个类似关键字的列表,该列表按其上周获得的点击次数排序。 Unfortunately I can't just use the counterCache 'click_count' field to do this because I need to only count clicks that occurred in the last week.
不幸的是,我不能只使用counterCache的“ click_count”字段来执行此操作,因为我只需要统计上周发生的点击。 To further complicate things I've got to add a LIKE() condition to the keyword field too.
为了进一步使事情复杂化,我还必须在关键字字段中添加一个LIKE()条件。
Here is what I've got so far: 这是到目前为止我得到的:
$result = $this->Keyword->find('all',array(
'conditions' => array(
'word_count >' => $keyword['Keyword']['word_count'],
'UPPER(keyword) LIKE' => "%".strtoupper($keyword['Keyword']['keyword'])."%"
),
'recursive' => 0,
'limit' => 10
));
I just need to add the bit that sorts these results by the number of associated Click records where Click.created is within the last week. 我只需要添加对这些结果进行排序的位,即可按上一周内Click.created所关联的Click记录数进行排序。 I've worked out that that part should look something like:
我已经计算出该部分应该看起来像:
array(
'conditions' => array(
'Click.created >' => date("Y-m-d",strtotime("1 week ago"))
),
'fields' => array(
'COUNT(Click.keyword_id) as count'
),
'group' => 'Click.keyword_id',
'order' => 'count DESC'
);
I'm just not sure where this bit should go. 我只是不确定这应该去哪里。
Please could someone put me out of my misery? 有人可以让我摆脱痛苦吗? Thanks :)
谢谢 :)
Well, I managed to blag an SQL query that does what I needed from this page: http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/ASP/Q_20646898.html 好吧,我设法对执行此页面所需的SQL查询进行标记: http : //www.experts-exchange.com/Web_Development/Web_Languages-Standards/ASP/Q_20646898.html
Here is what it looks like: 看起来像这样:
SELECT *
FROM keywords
AS Keyword
LEFT JOIN (SELECT keyword_id,count(*) AS click_count FROM clicks GROUP BY keyword_id)
AS Click
ON Keyword.id = Click.keyword_id
WHERE Keyword.word_count > ".$keyword['Keyword']['word_count']."
AND UPPER(Keyword.keyword) LIKE '%".strtoupper($keyword['Keyword']['keyword'])."%'
ORDER BY Click.click_count DESC
Hopefully someone else will find this useful. 希望其他人会发现这很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.