Search code examples
cakephp

Cakephp Avoid wrong condition between models


I am using cakephp 2.5, and need to join Vehicle table with Address table where vei_id is the foreign key

I have one find operation that is generating a wrong condition for the two models: Vehicle and Address.

Address has the vei_id column which is the foreign key to join the vehicle table.

The query is generating vehicle_id as the column to join the two tables, the problem is that this column does not even exists.

I have mapped the two models using the vei_id column.

How can I avoid this situation? seems cakephp try to guess the join column even if I have already write the condition using the column I want.

//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
                                            ),
                            )),
));

it generates this line:

LEFT JOIN Address ON (
    Address.vehicle_id = Vehicle.vei_id
    AND Address.vei_id = 'Vehicle.vei_id'
    AND Vehicle.vei_id = 123
)

Where this column does not exists:

Address.vehicle_id = Vehicle.vei_id

Solution

  • Your query looks little bit confusing:

    Just look at following conditions within contain:

    'contain' => array(
        'Address' => array('conditions'=>  
             array(
                'Address.vei_id'=>'Vehicle.vei_id', // why is this ?
                'Vehicle.vei_id' => $vehicleId
               ),
    ));
    

    Why are you using following conditions within contain ?

     Address.vei_id'=>'Vehicle.vei_id
    

    Did you do that to join two tables ?

    When you use contain these things are done by cakephp's convention. Address table is already joined with vehicle table.

    See here:Cakephp contain.

    Also why not to follow cakephp convention?

     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.
    

    These things also reduces your work and make things easier.

    See Here: (cakephp model and database conventions).