Linking Models Together

2019-09-12 03:29发布

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?

2条回答
老娘就宠你
2楼-- · 2019-09-12 03:48

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

}
查看更多
做个烂人
3楼-- · 2019-09-12 03:50

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

查看更多
登录 后发表回答