How to Retrieve fields from linked Models

会有一股神秘感。 提交于 2019-12-25 02:14:48

问题


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


来源:https://stackoverflow.com/questions/8050747/how-to-retrieve-fields-from-linked-models

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