Cakephp - contain (containable behavior) fetches too much

旧城冷巷雨未停 提交于 2019-12-23 12:17:18

问题


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:


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.



来源:https://stackoverflow.com/questions/18724491/cakephp-contain-containable-behavior-fetches-too-much

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