我正在使用cakephp 2.5,需要将Vehicle
表加入Address
表,其中vei_id
是外键
我有一个查找操作会为这两个模型生成错误的条件:Vehicle
和Address
。
Address
有vei_id
列,它是加入车辆表的外键。
查询生成vehicle_id
作为连接两个表的列,探测器是该列甚至不存在。
我使用vei_id
列映射了两个模型。
我怎样才能避免这种情况?似乎cakephp尝试猜测连接列,即使我已经使用我想要的列写了条件。
//Vehicle Model
public $hasOne = array(
'Address' => array(
'className' => 'Address',
'conditions' => array('Vehicle.vei_id = Address.vei_id'),
'foreignkey' => false
)
//Address Model
public $belongsTo = array(
'Vehicle' => array(
'className' => 'Vehicle',
'conditions'=> array('Vehicle.vei_id=Address.vei_id'),
'foreignKey' => 'vei_id'
),
);
//At vehiclecontroller
$data = $this->Vehicle->find('first', array(
'conditions' => array('Vehicle.vei_id' => $vehicleId),
'contain' => array(
'Address' => array('conditions'=> array('Address.vei_id'=>'Vehicle.vei_id',
'Vehicle.vei_id' => $vehicleId
),
)),
));
它生成这一行:
LEFT JOIN Address ON (
Address.vehicle_id = Vehicle.vei_id
AND Address.vei_id = 'Vehicle.vei_id'
AND Vehicle.vei_id = 123
)
此列不存在的位置:
Address.vehicle_id = Vehicle.vei_id
答案 0 :(得分:2)
您的查询看起来有点令人困惑:
只需查看以下条件:
'contain' => array(
'Address' => array('conditions'=>
array(
'Address.vei_id'=>'Vehicle.vei_id', // why is this ?
'Vehicle.vei_id' => $vehicleId
),
));
为什么在contains?
中使用以下条件? Address.vei_id'=>'Vehicle.vei_id
你这样做是为了加入两张桌子吗?
当你使用包含这些东西时,这是由cakephp的约定完成的。 地址表已经与车辆表联系在一起。
见这里:Cakephp contain。
为什么不遵循cakephp惯例?
If you have vehicles table,
the foreign key would be vehicle_id according to cakephp convention.
And if you have users table foreign key would be user_id.
这些事情也会减少你的工作并使事情变得更容易。