freshest
freshest

Reputation: 6241

Linking Models Together

I have the following three tables in a database:

Products
********
id
title
artist_id

Artists
*******
id
profile
rating
person_id

People
******
id
first_name
last_name

Each artist can have many products.

Each artist has only one person.

Each product has only one artist.

What are the correct associations to set up between the models for these three tables?

Upvotes: 0

Views: 93

Answers (2)

gustavotkg
gustavotkg

Reputation: 4399

I guess it is something like:

Product has an Artist:

<?php
class Product extends AppModel {
    var $hasOne = array('Artist');
}

Artist belongs to a Person and has many Products.

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

    var $belongsTo = array('Person');

    var $hasMany = array('Product');
}

Person has an Artist.

<?php
class Person extends AppModel {

    var $hasOne = array('Artist');

}

Upvotes: 0

Naftali
Naftali

Reputation: 146302

Artist to Products: One to Many
Product to Artist: One to One
Artist to Person: One to One

For example, the Artist Model:

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

    var $belongsTo = array(
        'Person' => array(
            'className' => 'Person',
            'foreignKey' => 'person_id'
        )
    );

    var $hasMany = array(
        'Product' => array(
            'className' => 'Product',
            'foreignKey' => 'product_id'
        )
    );
}
?>

DOC

Upvotes: 1

Related Questions