Domanda

I have two tables that I want to INNER JOIN, I spent hours but I had no luck. I will be very please if some could help.

My first table: properties

id | room | price | location_id

My second table is: locations

id | country | province | district

Note: location_id in Properties is 'id' in Location

I want to use basic model associations like hasOne, belongsTo and so on.

What should I put in my models so that I can basically get the following result?

SELECT
    Property.room,
    Property.price,
    Location.province
FROM
    properties AS Property
INNER JOIN locations AS Location ON Property.location_id = Location.id

Thanks in advance!

È stato utile?

Soluzione

The following model relation will generate the query you need.

class Property extends AppModel {

    public $belongsTo = array(
        'Location' => array(
            'type' => 'INNER'
        )
    );

}

Read more about model associations

Altri suggerimenti

Use the following code:

$this->Property->find('all', array('joins' => array(array('table' => 'locations',
                                   'alias' => 'Location',
                                   'type' => 'INNER',
                                   'conditions' => array('Property.LOCATION_ID = Location.ID')))));

Try this

class Location extends AppModel {

    public $belongsTo = array('Property'));

}

class Property extends AppModel {

    public $hasOne = array( 'Location'));

}

Try this :

class Variant extends AppModel {

    $this->bindModel(array('belongsTo' => array('Brand' => array('type' => 'INNER'))));

}

CakePHP does support a syntax for defining your own joins. It would be done like this, from the PropertiesController

$properties = $this->Property->find('all', array(
            'fields' => array('Property.*'),
            'joins' => array(
                array(
                        'table' => 'locations',
                        'alias' => 'Location',
                        'type' => 'INNER',
                        'conditions' => array(
                        'Property.location_id' =>'Location.id'
                        )
                    ),
                ),
            )
        );

Another Way You Can DO This

You would create a relationship with your Model, and use the containable behavior like below:

class Property extends AppModel {
    public $actsAs = array('Containable');
    public $belongsTo = array('Property');
}

class Location extends AppModel {
    public $actsAs = array('Containable');
    public $hasMany = array('Property');
}

Then you can do this from the PropertiesController:

$properties = $this->Property->find('all', array(
    'contain' => array('Location')
));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top