How to Retrieve fields from linked Models

2019-08-30 05:51发布

I have the following three database tables:

Products
########
id
title
artist_id

Arists
######
id
profile
person_id

People
######
id
first_name
last_name

In my Product model how do I create a method to return the product title along with the artist's first_name?

I have set up the following model associations:

Product belongs to Artist
Artist belongs to Person

2条回答
一夜七次
2楼-- · 2019-08-30 06:39

Containable is definitely the way to go for filtering related records. Make sure to add $actsAs = array('Containable') into your model or app_model.

Then you can do things like:

$this->Product->find('all', array(
    'contain' => array(
        'Artist' => array(
            'Person' => array(
                'id',
                'first_name'
            )
        )
    )
));
查看更多
霸刀☆藐视天下
3楼-- · 2019-08-30 06:47

Assuming you already set the relationships in these models, you just need to set it recursive:

$this->Product->recursive = 2;
print_r($this->Product->find('all'));
查看更多
登录 后发表回答