Cómo recuperar campos de modelos vinculados

I have the following three database tables:

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

Arists
######
id
profile
person_id

People
######
id
first_name
last_name

En mi 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

preguntado el 08 de noviembre de 11 a las 12:11

2 Respuestas

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

respondido 08 nov., 11:17

What is the actual syntax to just echo the first name? - más actualizado

Consulte nuestra página print_r to see the path. If you use $products = $this->Product->find('all') I guess it gonna be in $products[0]['Artist']['People']['first_name']. - gustavotkg

Funciona usando $products[0]['Artist']['Person']['first_name'], but using this method pulls a lot of unnecessary data, is there a better way to do this? - más actualizado

Puede usar el fields to choose which fields should be retrieved. See more here tuercas-y-pernos-de-cakephp.com/2008/08/06/… - gustavotkg

Think the Contenible behavior may be the way to go? - más actualizado

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

Entonces puedes hacer cosas como:

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

respondido 09 nov., 11:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.