Wednesday, August 4, 2010

1:n association: how to insert foreign key???

I know, this is a stupid question but I don't know how resolve this, I
have read a lot of docs but still don't understand.

I'm trying to create a biblio service and map Books/Authors,
I have SQL table for authors:

CREATE TABLE `authors` (
`id` int( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` varchar( 127 ) NOT NULL ,
`email` varchar( 127 ) NOT NULL ,
`website` varchar( 127 ) NOT NULL
);

and related model
<?php
class Author extends AppModel
{
var $name = 'Author';
var $hasMany = 'Book';
}
?>

and table for Books (with foreing key for author):
CREATE TABLE `books` (
`id` int( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`isbn` varchar( 13 ) NOT NULL ,
`title` varchar( 64 ) NOT NULL ,
`description` text NOT NULL ,
`author_id` int( 11 ) NOT NULL
)

and related model:
<?php
class Book extends AppModel
{ var $name = 'Book';
var $belongsTo = 'Author';
}
?>

It seems all ok, now I try to insert new book in DB (author will be
choose by a select form).
<?php
class BooksController extends AppController {
var $name = 'Books';
function add() {
if (!empty($this->data)) {
$this->Book->save($this->data);
}
$authors = $this->Book->Author->find('list');
$this->set('authors', $authors);
}
}
?>

and add view:
<?php echo $form->create('Book');?>
<fieldset>
<legend>Add New Book</legend>
<?php
echo $form->input('isbn');
echo $form->input('title');
echo $form->input('description');
echo $form->input('author_id');
?>
</fieldset>
<?php echo $form->end('Submit');?>

I've readed tons of manual, books and tutorial but the everything I
get when i try an add is:
Array to string conversion [CORE/cake/libs/model/datasources/
dbo_source.php, line 746]
SQL Error: 1054: Unknown column 'Array' in 'field list' [CORE/cake/
libs/model/datasources/dbo_source.php, line 681]

Probably that's why data is something like:
Array
(
[Book] => Array
(
[author_id] => Array
(
[0] => 15
)
[isbn] => dsadas
[title] => dsa
[description] => das
)
)

As you can see author_id value is not the right numeric value (15 in
this case) but array. That's cause the error.
Where is the mistake???

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