tags:

views:

61

answers:

4

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

A: 

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

Danylo Mysak
reverting to pure sql should be considered somehow last ressort as it has various drawbacks like: losing db-independency, introducing security risks.Kind regards
benjamin
+2  A: 

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
// ... //
?>
Leo
thanks but airline.operator is not a primary key
Web Developer
You misunderstand - here 'operator' is defined as the foreign key in the relationship. Cake knows on which table to find it as a result of the $hasOne or $belongsTo statement and will know to match it to 'id' on the Airline table (unless you have told Cake to use a different field).
Leo
+1  A: 

Hello Web Developer,

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 e.g. 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 e.g. a $belongsTo.

Kind regards, Benjamin.

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

This should work. just replace your fields