0

Lets say each book has AuthorA and AuthorB fields. Both fields are foreign keys for authors table.

table authors with fields: id | name

table books with fields: id | name | a_author_id | b_author_id |

How should controller, model and view be set up to be able to create a book with dropdown list of "author a" and "author b" both coming from author table? How would form-input for author-a (and author-b) look like inside "Add" view for Book model?

tereško
  • 58,060
  • 25
  • 98
  • 150
Gizzat
  • 39
  • 6

1 Answers1

1

You need to setup 2 belongsTo association in your Book model with different aliases for Author model.

public $belongsTo = array(
    'AAuthor' => array(
        'className' => 'Author',
        'foreignKey' => 'a_author_id'
    ),
    'BAuthor' => array(
        'className' => 'Author',
        'foreignKey' => 'b_author_id'
    )
);

Use $this->Book->AAuthor->find('list') to get the authors list and set the array to view and specify same array using 'options' key in Form->input() options for both a_author_id and b_author_id fields.

ADmad
  • 8,102
  • 16
  • 18
  • If Books can have multiple authors (not limited to a fixed amount), it's also possible to use a `HasAndBelongsToMany` relation. You'll have to change the database design to achieve this and things may be a bit more complicated when sorting/filtering books etc. – thaJeztah Mar 17 '13 at 10:21