PHP Activerecord模型计数关联 [英] PHP Activerecord Model Count Associations

查看:83
本文介绍了PHP Activerecord模型计数关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个表:

Member

MemberBranch

Branch

MemberMemberBranch可以有许多Branch.而且Branch可以有很多Member等.

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.

如此

$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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆