繁体   English   中英

Mysql:联接/关联两个表

[英]Mysql : Join/Relating two tables

我有两个桌子

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

我想将Airline.name与Form.operator相关联。 是否有可能因为Form.operator不是主键,如果可以,请给我查询。

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

我建议您不要使用系统中其他地方使用的名称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
// ... //
?>

为了像Leo所建议的那样建立关系,您必须遵循“蛋糕惯例”。 为了以后为您省去一些麻烦,因此,我建议在这里此处写得很好并且简短的材料。 您将了解到,例如Cakephp可以为您完成一些工作的一个很好的外键称为operator_id ,而不是简单的operator (如果operator还不是外键,则可能是您有数据库设计问题)。 此处的提升是指自动识别曾经在$ belongsTo中定义的关系。

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

这应该工作。 只需替换您的字段

select * from `airline`, `form` where `airline.id`=`form.operator`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM