Question

Tables

User(id)
Profile(id, *user_id*, type)
Attribute(id, *attribute_name_id*, value)
AttributeName(id, name)
ProfileAttribute(id, *profile_id*, *attribute_id*)

Relationships

The relationships are set up correctly (and go both ways, hasMany/belongsTo).

User hasMany Profile
Profile hasMany ProfileAttribute
Attribute hasMany ProfileAttribute
  (could be written Profile hasMany Attribute through ProfileAttribute)
AttributeName hasMany Attribute

Goal

For a specified User id, with a find() in the User model, I only want the following fields, laid out as such:

$results[Profile.type][AttributeName.name][Attribute.value]

Is it even possible to retrieve results arranged like this? I've been playing around with Find and Containable for hours, but, first time trying to do anything complicated like this with Cake, I can't get the hang of it.

Thanks!

EDIT

I'm getting these results now, all that I need, but nowhere near the desired format above -can it be done as part of the find, or does it need to be sorted after?

Was it helpful?

Solution

Yep, it's possible. You just have to specify fields on containable:

$this->User->find('all', array(
    'conditions' => array('User.id' => $id),
    'fields' => array('id'),
    'contain' => array(
        'Profile' => array(
            'fields' => array('id','type'),
            'ProfileAttribute' => array(
                'fields' => array('id'),
                'AttributeName' => array(
                    'fields' => array('id','name'),
                    'Attribute' => array(
                        'fields' => array('id','value')
                    )
                )
            )
        )
    )
);

Be wary that when you use contain and fields options, you have to specify the id so it can make the association (check the docs)

EDIT: I don't know if you can group contained data as the docs didn't say anything about that, but probably you can, as they accept some parameters as in the main query. You can try it, adding group to any contained data that you want to group

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top