Linking Models Together

2019-09-12 03:44发布

问题:

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?

回答1:

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



回答2:

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');

}