Friday, July 23, 2010

Re: HABTM and foreign keys on delete cascade

Because you chose HABTM, you've said that an Author can write many
books, and a book can have many Authors. If you delete the author, it
won't delete the book because other Authors have written that book,
too. I think you're looking for a hasMany / belongsTo association.

Author -> hasMany Book
Book -> belongsTo Author

This isn't going to have a join table, but the books table is going to
have an author_id field. That's probably going to give you more what
you're looking for.

Hope that helps.

On Jul 23, 7:31 am, "Mariano C." <mariano.calan...@gmail.com> wrote:
> I have the usual example about books and authors.
> I have followed CakePHP naming convention and I'm on MySQL without
> InnoDB so I can't write foreign key constraints directly on db.
>
> I have 3 tables authors, books and authors_books. The last table has 3
> fields: id as PK, author_id and book_id.
>
> Two model for books and authors, associated by HABTM "link". All that
> I want realize is: as soon I remove an author, even the book written
> by this author must be deleted.
>
> Book model:
> <?php
> class Book extends AppModel
> {
>     var $name = 'Book';
>     var $hasAndBelongsToMany = 'Author';}
>
> ?>
>
> Author model:
> <?php
> class Author extends AppModel
> {
>     var $name = 'Author';
>     var $hasAndBelongsToMany = array
>         (
>             'Album' => array
>             (
>                  'className' => 'Book',
>                         'dependent' => true
>             )
>         );}
>
> ?>
>
> delete() function in authors_controller.php (AuthorsController)
> <?php
> function delete($id)
>     {
>         $del = $this->Author->findById($id);
>         $this->Author->delete($id, true);
>         $this->Session->setFlash('The author \''.$del['Author']
> ['name'].'\' has been deleted.');
>         $this->redirect(array('action'=>'index'));
>     }
> ?>
>
> Now, if I delete an author, in MySQL will be deleted the author from
> authors table, the relative record in join table (authors_books) that
> bind author deleted with his book, but nothin change in books table.
>
> Why???

Check out the new CakePHP Questions site http://cakeqs.org and help others with their CakePHP related questions.

You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php?hl=en

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate