duankuixi1930 2014-01-22 18:24
浏览 25
已采纳

PHP Activerecord模型计数关联

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?

  • 写回答

2条回答 默认 最新

  • drap5081683 2014-01-23 09:47
    关注

    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 :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误