我想生成一个与habtm关系的列表(下拉列表)。例如,我有一个名为“users”的表,另一个名为“vehicles”和“users_vehicles”。
我想要的是将车辆分配给“x”用户并将其放入下拉列表中。我怎样才能做到这一点?
class User extends AppModel { var $hasAndBelongsToMany = array('Vehicle'); }
答案 0 :(得分:3)
这是一种方式,可能还有其他几种方式。
$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');
答案 1 :(得分:1)
<code>
$options['conditions']['Ownership.vehicle_id'] = $x;
$options['joins'] = array(
array(
'table' => 'ownership',
'alias' => 'Ownership',
'type' => 'Left',
'conditions' => 'Vehicle.id = Ownership.vehicle_id'
)
);
$this->set('vehicles', $this->Vehicle->find('list', $options));
</code>