Linking Models Together

[亡魂溺海] 提交于 2019-12-13 06:57:49

问题


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

}


来源:https://stackoverflow.com/questions/8052833/linking-models-together

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!