tags:

views:

471

answers:

1

Hi.

I want to generate a list (dropdown) with habtm relationship, for example i have a table called "users" another called "vehicles" and "users_vehicles".

What i want is to get vehicles assigned to "x" user and put it in a dropdown, how i can achieve this?


class User extends AppModel {

   var $hasAndBelongsToMany = array('Vehicle');
}

+1  A: 

This is one way, there a probably several others.

$result = $this->User->Vehicle->find('all', array(
    'recursive' => -1,
    'conditions' => array('Ownership.user_id' => 66),
    'fields' => array('Vehicle.*','Ownership.*'),
    'joins' => array(
     array(
      'table' => 'users_vehicles',
      'alias' => 'Ownership',
      'type' => 'LEFT',
      'foreignKey' => false,
      'conditions'=> 'Vehicle.id = Ownership.vehicle_id'
     )
    )
));
$list = Set::combine($result,'{n}.Vehicle.id','{n}.Vehicle.name');
Alexander Morland