pt0
pt0

Reputation: 175

Correct model associations in cakephp

I use HABTM to populate database. I have 3 models. User, Book, Comment. To join records in the tables books and users I use in HABTM users_books table, and to bind comments I use 2 primary keys, user_id and book_id, which both are set as foreign key:

PRIMARY KEY (user_id, book_id)
FOREIGN KEY (user_id, book_id) REFERENCES users_books (user_id, book_id)

Table books, and users_books are being populated but in some cases I can get the comment table populated but only with user_id and book_id, other data is NULL. Or Iif I remove user_id (Comment array) from the saveAll query I got:

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails 

So I guess it is either against the cakephp conventions or I am doing something wrong.

Here is the part of Model Book:

  public $hasAndBelongsToMany = array(
  'User' =>
  array(
    'className' => 'User',
      'joinTable' => 'users_books',
        'foreignKey' => 'book_id',
        'associationForeignKey' => 'user_id',
        'unique' => true,
    'conditions' => '',
    'fields' => 'book_id',
    'order' => '',
    'limit' => '',
    'offset' => '',
    'finderQuery' => '',

),
'Comment' =>
array(
  'className' => 'Comment',
  'joinTable' => 'comments',
  'foreignKey' => 'book_id',
  'associationForeignKey' => 'user_id',
  'unique' => true,
  'conditions' => '',
  'fields' => '',
  'order' => '',
  'limit' => '',
  'offset' => '',
  'finderQuery' => '',),);

And Comment:

public $belongsTo = array (
'Book' => array (

'foreignKey'=>false,
'conditions'=> array('Comment.book_id = UserBook.book_id')));

edit:

Data to save

$this->request->data['Book']['title'] = "title".rand(1,1220);
$this->request->data['Book']['author'] = "author".rand(1,1220);
$this->request->data['User']['id'] = $this->Auth->user('id');
$this->request->data['Book']['Comment']['body'] = "cm: ".rand(1,1220);
$this->Book->save($this->request->data, array('deep'=>TRUE));

And the save call:

  $this->Book->saveAll($this->request->data, array('deep'=>TRUE));

Upvotes: 0

Views: 100

Answers (1)

Laura
Laura

Reputation: 71

I think that the request data array is not in the correct form for cakephp to save correctly. Can you post the array? you can add this line before save() function:

pr($this->request->data);

See this link: Saving HABTM

Upvotes: 1

Related Questions