如何从链接模型中检索字段


How to Retrieve fields from linked Models

我有以下三个数据库表:

Products
########
id
title
artist_id
Arists
######
id
profile
person_id
People
######
id
first_name
last_name

在我的Product模型中,我如何创建一个方法来返回产品title和艺术家的first_name

我已经建立了以下模型关联:

Product belongs to Artist
Artist belongs to Person

Containable无疑是过滤相关记录的方法。确保将$actsAs=数组('Container'(添加到您的模型或app_model中。

然后你可以做一些事情,比如:

$this->Product->find('all', array(
    'contain' => array(
        'Artist' => array(
            'Person' => array(
                'id',
                'first_name'
            )
        )
    )
));

假设您已经在这些模型中设置了关系,您只需要将其设置为recursive:

$this->Product->recursive = 2;
print_r($this->Product->find('all'));