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
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 开发者_如何学JAVAsimilar keywords ordered by the number of clicks they've received in the last week. 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. To further complicate things I've got to add a LIKE() condition to the keyword field too.
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. 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
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.
精彩评论