Caio Norder February 2016

hasAndBelongsToMany in CakePHP 2.x

I need help for the simple relationchip in cakephp 2.x, I believe this right however not working:

Customer.php (Model)

public $hasAndBelongsToMany = array(
    'Note' => array(
        'className' => 'Note',
        'joinTable' => 'customers_notes',
        'foreignKey' => 'customer_id',
        'associationForeignKey' => 'note_id',
        'unique' =>false,
        'dependent'=>true,
    )
);

Note.php (Model)

public $hasAndBelongsToMany = array(
    'Customer' => array(
        'className' => 'Customer',
        'joinTable' => 'customers_notes',
        'foreignKey' => 'note_id',
        'associationForeignKey' => 'customer_id',
        'unique' =>false,
        'dependent'=>true
    )
);

CustumersController.php (Controller I make the find)

public function admin_notes($id=null){
    $this->layout="Adm.admin";

    $all = $this->Customer->Note->find('all', array(
        'limit' => 10,
        'conditions' => array(
            "CustomersNote.customer_id" => $id
        ),
        'order'=>'CustomersNote.id DESC'
    ));
    $this->set('notes', $all);
}

The error

SQL Query: SELECT `Note`.`id`, `Note`.`titulo`, `Note`.`conteudo`, `Note`.`created`, `Note`.`modified`, `Note`.`user_id` FROM `crm_prado`.`notes` AS `Note` WHERE `CustomersNote`.`customer_id` = '1' LIMIT 10

Thanks!

Answers


Caio Norder February 2016

The soluction is really simple.

In find uses

$all = $this->Customer->find('all', array(
        'recursive'=>2,
        'conditions'=>array(
            'Customer.id'=>$id
        )
 ));

Works!, but now the recursive mode don't work...

Post Status

Asked in February 2016
Viewed 2,259 times
Voted 12
Answered 1 times

Search




Leave an answer