Mysql:加入/关联两个表

时间:2010-08-25 07:44:56

标签: php mysql cakephp

我有两张桌子

1. Airline -id(primary), name
2. Form - id(primary), operator, other unwanted fields

我想将Airline.name与Form.operator联系起来。是否可能因为Form.operator不是主键,如果是,请给我查询。

有人可以指导我,在这种情况下,cakephp模型的关系如何

4 个答案:

答案 0 :(得分:2)

我建议你不要像在系统中的其他地方那样使用名称Form,但是试试这个(或类似的东西)并阅读http://book.cakephp.org/view/1039/Associations-Linking-Models-Together

在app / models / airline.php中:

<?php
class Airline extends AppModel
{
    var $name = 'Airline';

    var $hasOne = array(
        'Form' => array(
        'className' => 'Form',
        'foreignKey' => 'operator')
        );

// other stuff
// ... //
?>

在app / models / form.php中:

<?php
class Form extends AppModel
{
    var $name = 'Form';

    var $belongsTo = array(
        'Airline' => array(
        'className' => 'Airline',
        'foreignKey' => 'operator')
        )
    ;
// other stuff
// ... //
?>

答案 1 :(得分:1)

为了建立关系,正如Leo建议的那样,你必须遵循蛋糕惯例。为了避免以后出现一些令人头疼的问题,我建议使用编写得很好的短材料herehere。你会学到例如cakephp可以为你做一些好的外键,名为operator_id,而不仅仅是operator(如果运算符不是外键,可能是因为你有数据库设计问题)。 这里提升指的是自动识别一旦在例如中定义的关系。 a $ belongsTo。

答案 2 :(得分:1)

var $hasOne = array(
    'airline' => array(
        'className' => 'airline',
        'foreignKey' => false,
        'conditions' => array(
            '`form`.`yourfield` = `airline`.`yourfield`'
        )
    )
}

这应该有效。只需替换你的字段

答案 3 :(得分:0)

select * from `airline`, `form` where `airline.id`=`form.operator`
相关问题