简体   繁体   中英

Add new Book for Author

I'm new to Laravel so the solution to this may be quite simple. I have an already created Author and I'm trying to add a new book for that Author.

For example, on the Author view there will be an "Add new Book" button. When clicked, you are taken to the "Create new Book" view with the Author id already provided from the previous view.

Author model has a hasMany to Books
Books model has a belongsTo Author

What is the cleanest way to achieve this?

$book= new Book(array('name' => 'your new book here'));

$author= Author::find(1);

$book= $author->books()->save($book);

You can read more about inserting related models here in the official Laravel docs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM