Alvaro
Alvaro

Reputation: 41605

Get all the belongsTo relations plus some HABTM at CakePHP

I'm trying to get only one HABTM relationship when using paginate using CakePHP 2.3.

Right now I'm getting this result:

Array
(
    [0] => Array
        (
            [Ticket] => Array ( .....)
            [User] => Array ( .....)
            [Priority] => Array ( .....)
            [Status] => Array(....)
            [Attachment] => Array(....)
            ....
        )
    [1] => ....
    [2] => ....

)

By using:

    $this->Ticket->recursive = 0;
    $this->paginate = array(
            'limit' => 20
    );

I am using $this->Ticket->recursive = 0; because I'm only interested in the belongsTo relationships with other tables, but at the same time, I would like to get only one of the HABTM relationships.

I know I could achieve it adding each of the single relationships in the contain array, like so:

    $this->Ticket->recursive = 0;
    $this->paginate = array(
            'limit' => 20,
            'contain' => array(
                    'Ticket`, `User`, `Priority`, `Status`, `Attachment`, `Tags`...
            )
    );

But I have plenty of tables and I was wondering if there's any way to do it without having to name every single table in the contain array.

I've also tried to use the recursive array inside the contains one like so:

    //getting the filtered tickets
    $this->paginate = array(
            'limit' => 20,
            'contain' => array(
                    'Ticket' => array('recursive' => 1),
                    'Tag' //this is the hasMany relationship 
            )
    );

But it didn't work. Is there any way to achieve this without having to name all the tables to make it more simple to maintain?

Upvotes: 1

Views: 91

Answers (1)

Alvaro
Alvaro

Reputation: 41605

Ok, as it seems there's no solution for it, I managed to do it by getting the associated models of the type belongsTo and then adding the model name of the HABTM relationship:

$associations = $this->Ticket->getAssociated('belongsTo');
$associations[] = 'Tag';

//getting the filtered tickets
$this->paginate = array(
        'limit' => 20,
        'contain' => $associations
);

Upvotes: 1

Related Questions