简体   繁体   中英

Laravel Database many:one relation

I'm learning laravel and building a small blog application to practice.

I have a 'posts' table with the following structure:

id:int AI
post:text
author:int

And a comments table with the following structure:

id:int AI
comment:text
author:int
post:int

Where the post field in the comments table is meant to link the comment to the its post.

Now, in order to add a comment, I would add a form in my show.blade.php file in the views/posts directory and point it to the store@CommentsController metod. A hidden field of the view would be automatically populated with the post's ID, so that my store method in Comments Controlelr could look something like:

Post::find(id)->comments->save($comment);

(I'd have already defined the relations between the tables in the model fiels, and $comment would be something like $comment = Comment::create($comment_data_from_form) )

That would be all and well, however, I was wondering if laravel had some nicer way of passing the id of the post from the post view to the comments controller than having to specify and populate a hidden field?

You could use a route with the post id as a parameter.

To create a new comment for a post you could use a route like following.

http://example.org/posts/{id}/comments

and in your controller

public function store($postId)
{
    $post = Post::findOrFail($postId);
    ...
    $post->comments->save($comment);
}

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