freshest
freshest

Reputation: 6241

Model Associations and Data Modelling

I am developing a web app for an art gallery, and I want to check I have set up the data model correctly.

I have a people table and an artists table. Some of the people are artists and some are not.

I also have a products table and each product belongs to one artist.

Below is a simplified version of the tables:

products
********
id
title
artist_id

artists
*******
id
profile
rating
person_id

people
******
id
first_name
last_name

I need to be able to retrieve the name of the artist when performing the find() method on the Product model.

Have I set up the data model correctly and if so what is the best way to retrieve the artist's name without getting lots of unwanted data?

Upvotes: 0

Views: 134

Answers (2)

Moz Morris
Moz Morris

Reputation: 6771

It's possible to use CakePHP's bindModel & unbindModel to build up relations that don't rely on Cake's automagic goodness.

Since you were interested in doing the find on the Product model, I'll set out an example that can be called from the Products controller:

// unbind Artist
$this->Product->unbindModel(array(
  'belongsTo' => array('Artist')
));

// bind Artist & Person using explicit conditions
$this->Product->bindModel(array(
  'hasOne' => array(
    'Artist' => array(
      'foreignKey' => false,
      'conditions' => array('Artist.id = Product.artist_id')
    ),
    'Person' => array(
      'foreignKey' => false,
      'conditions' => array('Person.id = Artist.person_id')
    ),
  )
));

// return the person
$person = $this->Product->find('first', array(
  'conditions' => array(
    'Product.id' => 1 // or any other condition
  ),
  'fields' => array(
    'Person.first_name',
    'Person.last_name'
  )
));

What's happening here?

Firstly, we unbind the Product model's relationship with the Artist model.

Secondly, we bind the Artist and Person models by explicitly defining the relationships and disabling Cake's automatic forigenKey connections.

Lastly, we do a 'first' find on the Product model and only request the 'first_name' & 'last_name' of the Person.

Upvotes: 3

petervaz
petervaz

Reputation: 14205

Each 'Product' belongs to an 'Artist' and each 'Artist' hasAndBelongsToMany 'Product' You will also need the following table:

artists_products
****************
id
product_id
artist_id

http://book.cakephp.org/#!/view/1044/hasAndBelongsToMany-HABTM

Upvotes: -1

Related Questions