aWebDeveloper
aWebDeveloper

Reputation: 38402

Cakephp model relation

I have two tables user and location

user has id(primary) and location fields/columns

location has id(primary) and city column

Now i wish to relate the two tables by user.location with location.city How can i do it considring city is not a primary key but is unique. I am using cakephp 1.2.

Also in mysql can i relate/join tables without primary key but a unique key

Upvotes: 0

Views: 264

Answers (1)

dogmatic69
dogmatic69

Reputation: 7585

Either in the model or with on the fly binding you can create joins with non primary keys as follows

public $hasOne = array(
    'RelatedModel' => array(
        'className' => 'RelatedModel',
        'foreignKey' => false,
        'conditions' => array(
            '`MainModel`.`random_field` = `RelatedModel`.`some_field`'
        )
    )
}

the trick is setting foreignKey to false so cake does not try anything and then setting the conditions manualy, also note that the fields are excaped and in one string as something like

'`MainModel`.`random_field`' => '`RelatedModel`.`some_field`'

would output

SELECT ..... FROM ... LEFT JOIN ... ON (`MainModel`.`random_field` = '`RelatedModel`.`some_field`')

which would try join rows that == 'RelatedModel.some_field' (the actual string)

Upvotes: 1

Related Questions