Kohana 3 ORM: Getting most repeated values, ranked, and inserting into new object / array
So, another in my series of Kohana 3 ORM questions :)
I have, essentially, a pivot table, called connections
. The connections
table connects a song
to a keyword
. That's all great and working (thanks to my last two questions!)
I want to output the most connected songs by keyword. So, to somehow query my connections
table and output an object (with an arbitrarily limited number of iterations $n
) that ranks songs by the number of times they hav开发者_如何学Pythone been connected, ie. the number of times that particular song_id
appears for that particular keyword_id
.
I have literally no idea how to achieve this, without querying every single row (!!!) and then counting those individual results in an array.... There must be a more elegant way to achieve this?
I believe this is more of an SQL question. Using the DB query builder:
DB::select('songs.*')->select(array('COUNT("keywords.id")', 'nconnections'))
->from('songs')
->join('connections', 'LEFT')->on('connections.song_id', '=', 'songs.id')
->join('keywords', 'LEFT')->on('connections.keyword_id', '=', 'keywords.id')
->group_by('songs.id')
->order_by('nconnections')
->as_object('Model_Song')
->execute();
or in SQL
SELECT `songs`.*, COUNT(`keywords`.`id`) AS `nconnections` FROM songs
LEFT JOIN `connections` ON `connections`.`song_id` = `songs`.`id`
LEFT JOIN `keywords` ON `connections`.`keyword_id` = `keywords`.`id`
GROUP BY `songs`.`id` ORDER BY `nconnections`
should return the result you want.
You'll want to have an accessible property called nconnections
in your song model. The simplest way to do that is to add a public member so you don't tamper with ORM's inner workings.
I'm assuming you're using a model called 'Song', linked to a 'songs' table, a 'Keyword' model linked to a 'keywords' table and in the 'connections' table foreign keys 'song_id' and 'keyword_id' for each model respectively.
精彩评论