PHP Activerecord Model Count Associations

纵饮孤独 提交于 2020-01-17 03:04:04

问题


I have three tables:

Member

MemberBranch

Branch

The Member can have many Branches through MemberBranch. And a Branch can have many Members 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!