开发者

Cakephp model relation

I have two tables user and location

user has id(primary) and location fields/columns

location has id(primary) a开发者_开发百科nd 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


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜