PHP Activerecord模型计数关联 [英] PHP Activerecord Model Count Associations
问题描述
我有三个表:
Member
MemberBranch
Branch
Member
到MemberBranch
可以有许多Branch
.而且Branch
可以有很多Member
等.
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.
如此
$branch = Branch::find_by_title('London');
$branch->number_of_members; // Will equal how many members have the branch through MemberBranch
我将如何去做?
推荐答案
以防万一其他人有类似的问题,我已经找到了解决方案(尽管有点hacky)
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`'
)
);
}
这将创建一个新的关联,但会使用select属性执行我们想要的SQL查询.现在可以按以下方式访问每个分支的成员数:
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
我使用$has_one
而不是$has_many
的原因是,即使只有一个对象,$has_many
也将始终返回对象的array
.因此使用$has_many
意味着要像这样访问总数:
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
保存击键:)
这篇关于PHP Activerecord模型计数关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!