How can a sort by user popularity when using a hasAndBelongsToMany table relationship? ie:
I have a table called playgroups, players, and playgroup_players.
How can I sort playgroups by the number of players in the playgroup?
Playgroups:
CREATE TABLE `playgroups` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`tag` varchar(4) COLLATE utf8_unicode_ci DEFAULT NULL,
`description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`avatar_url` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`city` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`state` varchar(2) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Players:
CREATE TABLE `players` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(30) DEFAULT NULL,
`last_name` varchar(30) DEFAULT NULL,
`username` varchar(30) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`public_email` tinyint(1) NOT NULL DEFAULT '0',
`facebook_id` varchar(250) DEFAULT NULL,
`card_tooltip` tinyint(1) NOT NULL DEFAULT '1',
`profile_pic_url` varchar(255) NOT NULL,
`public_name` tinyint(1) NOT NULL DEFAULT '0',
`city` varchar(40) NOT NULL,
`state` varchar(2) NOT NULL,
`date_joined` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=107 DEFAULT CHARSET=latin1;
And PlaygroupPlayers:
CREATE TABLE `playgroup_players` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`player_id` int(11) NOT NULL,
`playgroup_id` int(11) NOT NULL,
`admin` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
This will give you a list of playgroups that have at least one player sorted by the number of players. Of course, field name is made up 🙂
This should give you a list of ALL playgroups (even the ones with no players). I’ve tested this on Oracle and on some of my own data and it works