简体   繁体   中英

CakePHP 2.x HABTM returning is no matching results

I have a problem with habtm with cakephp and i dont know how to solve yet. I've got three tables: setores, veiculos e setores_veiculos.

Setor model:

public $hasAndBelongsToMany = array(
    'Veiculo' => array(
        'className' => 'Veiculo',
        'joinTable' => 'setores_veiculos',
        'foreignKey' => 'setor_id',
        'associationForeignKey' => 'veiculo_id',
        'unique' => 'keepExisting'
    )
);

Veiculo model:

public $hasAndBelongsToMany = array(
    'Setor' => array(
        'className' => 'Setor',
        'joinTable' => 'setores_veiculos',
        'foreignKey' => 'veiculo_id',
        'associationForeignKey' => 'setor_id',
        'unique' => 'keepExisting'
    )
);

In my setores controller i have:

$options = array('conditions' => array('Setor.' . $this->Setor->primaryKey => $id));    
$setores = $this->Setor->find('first', $options);

then in my debug:

array(
'Setor' => array(
    'id' => (int) 5,
    'nome' => '2º Batalhão',
    'secretaria_id' => (int) 6,
    'sigla' => '2º BPM',
    'status_id' => (int) 1
),
'Veiculo' => array()
)

I can not understand why the Veiculo (vehicle) are not being listed. The insertion is working perfectly.

I expected:

 'Veiculo' => array(
     0 => array(
        'id' => 1,
        'name' => 'Corolla'
     ),
     1 => array(
          'id' => 2,
        'name' => 'Hillux'
    )
  );

In my veiculos controller the setores are being listed. Any suggestion?

Thank you in advance and sorry about my english.

Looks fine to me. Try changing

'unique' => 'keepExisting'

to

'unique' => true

At present, I go by the simple rules as explained in the documentation that if I am using a simple link table, ie not storing any data in it, I use HABTM and unique set to true , otherwise I use hasMany through (The Join Model) and unique set to keepExisting so as not to lose extra stored data.

Post a data dump of setores_veiculos.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM