问题
I have three tables:
Member
MemberBranch
Branch
The Member
can have many Branch
es through MemberBranch
. And a Branch
can have many Member
s etc.
What I want to be able to do is get a count of how many members a branch has.
so
$branch = Branch::find_by_title('London');
$branch->number_of_members; // Will equal how many members have the branch through MemberBranch
How would I go about doing this?
回答1:
Try this:
SELECT B.*, (SELECT count(*) as total from MembersBranch where branch_id = B.id) as total FROM Branch AS B;
回答2:
Just incase anyone else has a similar problem, I have found a solution (albeit a little hacky)
class Branch extends \ActiveRecord\Model {
static $has_one = array(
array(
'members',
'class_name' => 'MemberBranch',
'primary_key' => 'id',
'foreign_key' => 'branch_id',
'select' => 'COUNT(`membership_id`) AS `total`'
)
);
}
This creates a new association but does the SQL query we want using the select property. The number of members per branch can now be accessed like:
$branch->members->total
The reason I used $has_one
as opposed to $has_many
is that $has_many
will always return an array
of objects even if there is only one object. so using $has_many
would have meant accessing the total like so:
$branch->members[0]->total
Save your keystrokes :)
来源:https://stackoverflow.com/questions/21290934/php-activerecord-model-count-associations