简体   繁体   中英

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. Is it possible since Form.operator is not primary key, if yes give me the query.

Can some one also guide me as how will the cakephp model relation be in this case

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

In 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:

<?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. 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). Lifting here refers to automatically recognizing relations once defined in eg a $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`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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