Cakephp - contain (containable behavior) fetches t

2019-06-24 19:19发布

As I understood from the cakephp-documentation, one of the advantages of the 'containable'-Behavior is being able to fetch fewer data if you need fewer data...

But that doesn't seem to work in my case of a connection between users and usergroups.

My associations look like:

    Group
    hasMany: Membership

    User
    hasMany: Membership

    Membership
    belongsTo: User, Group

(I'm not using HABTM, instead use the Model 'Membership' in between to join users and groups).

All Models implement the 'Containable'-Behavior.

Now I want to get all the members of a group with a certain id, only their ids and mail-addresses. My query is built like that:

    $members = $this->Membership->find('all', array(
        'conditions'    => array(
                'group_id'      => $id
            ),
        'contain'       => array(
            'User'          => array(
                'fields' => array('id', 'fullName')
            ),
        )
    ));

But the resulting array looks like:

array(
    (int) 0 => array(
            'Membership' => array(
            'id' => '1',
            'group_id' => '1',
            'user_id' => '1',
            'role' => 'member'
        ),
        'Group' => array(
            'id' => '1',
            'name' => 'Foo Group'
        ),
        'User' => array(
            'password' => '*****',
            'id' => '1',
            'name' => 'Dr. Foo'
            'mail' => 'foo@bar.baz',
            'role' => 'admin'
        )
    )
)

So there are definietely more fields fetched than I wanted to... (it's the same thing btw wenn I set the 'contain'-key to:

    'contain'   => array(
        'User.fullName', 'User.id'
    )

Am I using the containable-behavior wrong?

1条回答
够拽才男人
2楼-- · 2019-06-24 20:09

Your models don't seem to be acting containabl-y at all. Have you set your models to act as containable?

class Post extends AppModel {
    public $actsAs = array('Containable');
}

If so, maybe the problem is with the recursion (to avoid getting the Group array with the query). Containable behavior should handle the recursion level on its own, but try setting it on the AppModel just to be sure

class AppModel extends Model {
    public $actsAs = array('Containable');
    public $recursive = -1;

Your first attempt

    'contain'       => array(
        'User'          => array(
            'fields' => array('id', 'fullName')
        ),
    )

looks good in terms of syntax, so it probably the actAs thing.

Also, for debugging also, try

$this->Membership->contain('User');
$this->Membership->find('all', array(
    'conditions'    => array(
            'group_id'      => $id
        ));

and see if you get the expected results that way.

查看更多
登录 后发表回答