How to Retrieve fields from linked Models

2019-08-30 06:23发布

问题:

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

回答1:

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


回答2:

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