tags:

views:

41

answers:

1

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

+1  A: 

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)

dogmatic69
would try it out and what about mysql part of my question
Web Developer
have you tried this? dont you think if mysql could not do this i would say so, instead of giving you a whole lot of code. you can join on anything you like
dogmatic69
thanks for the insight
Web Developer
it works but are there any other ways
Web Developer
that is *the* way, how else do you want to do it?
dogmatic69