Max Doumit
Max Doumit

Reputation: 1115

Cakephp 2.0 format inner join output

I need to format the following cake php join without having to run an ugly php script in my controller.

here is my cakephp join

$this->Type->find('all' , array(
        'conditions' => array( 'Type.id' => '2' ),
        'joins' => array(
          array(
            'table' => 'subtypes',
            'alias' => 'Subtype',
            'conditions' => 'Subtype.tid = Type.id'
         )
      )
 ));

And here is the output i get

Array
(
    [0] => Array
        (
            [Type] => Array
                (
                    [id] => 4
                    [name] => Clay
                    [handle] => CL
                    [description] => 
                )

            [Subtype] => Array
                (
                    [id] => 11
                    [tid] => 4
                    [name] => Water Based
                )

        )

    [1] => Array
        (
            [Type] => Array
                (
                    [id] => 4
                    [name] => Clay
                    [handle] => CL
                    [description] => 
                )

            [Subtype] => Array
                (
                    [id] => 12
                    [tid] => 4
                    [name] => Oil Based
                )

        )
)

And here is the output that i want

Array
(
    [0] => Array
        (
            [Type] => Array
                (
                    [id] => 4
                    [name] => Clay
                    [handle] => CL
                    [description] => 
                )

            [Subtype] => Array(
                [0] => Array(
                    [id] => 11
                    [tid] => 4
                    [name] => Water Based
                )
                [1] =>Array
                (
                    [id] => 12
                    [tid] => 4
                    [name] => Oil Based
                )
            )
        )
)

How can i achieve this ??

Thank you alot ^^

Upvotes: 0

Views: 2269

Answers (2)

huzefam
huzefam

Reputation: 1191

You can use Model Association in Cakephp instead of using joins

For your reference :- http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

If you need any help do let me know!

Upvotes: 2

mark
mark

Reputation: 21743

dont use joins. use relations and containable

public $hasMany = array('Subtype'); // your foreign key should be "type_id" not "tid"

and

$this->Type->find('all', array(
    'conditions' => array('Type.id' => '2'),
    'contain'=>array('Subtype')));

Upvotes: 1

Related Questions