简体   繁体   English

Mysql:联接/关联两个表

[英]Mysql : Join/Relating two tables

I have two table 我有两个桌子

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

I want to relate Airline.name to Form.operator. 我想将Airline.name与Form.operator相关联。 Is it possible since Form.operator is not primary key, if yes give me the query. 是否有可能因为Form.operator不是主键,如果可以,请给我查询。

Can some one also guide me as how will the cakephp model relation be in this case 在这种情况下,cakephp模型的关系将如何,也可以有人指导我吗?

I would advise you to not use the name Form as is it used elsewhere in the system, however try this (or something similar) and read http://book.cakephp.org/view/1039/Associations-Linking-Models-Together 我建议您不要使用系统中其他地方使用的名称Form,但是请尝试使用此名称(或类似名称)并阅读http://book.cakephp.org/view/1039/Associations-Linking-Models-Together

In app/models/airline.php: 在app / models / airline.php中:

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

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

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

In app/models/form.php: 在app / models / form.php中:

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

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

in order to make the relations, as Leo suggested, work, you have to follow the cake conventions. 为了像Leo所建议的那样建立关系,您必须遵循“蛋糕惯例”。 In order to save you some headaches later on, I would therefore suggest the nicely written and short material here and here . 为了以后为您省去一些麻烦,因此,我建议在这里此处写得很好并且简短的材料。 You will learn eg that a good foreign key for which cakephp can do some lifting for you is named operator_id , instead of simply operator (if operator is not yet a foreign key, it could be that you have a database design issue). 您将了解到,例如Cakephp可以为您完成一些工作的一个很好的外键称为operator_id ,而不是简单的operator (如果operator还不是外键,则可能是您有数据库设计问题)。 Lifting here refers to automatically recognizing relations once defined in eg a $belongsTo. 此处的提升是指自动识别曾经在$ belongsTo中定义的关系。

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

This should work. 这应该工作。 just replace your fields 只需替换您的字段

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

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

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