Laravel attach() method not working to hasMany side

前端 未结 4 1490
孤街浪徒
孤街浪徒 2020-12-18 21:34

The application has the models:

Atividade.php

class Atividade extends Eloquent {
    public function interv         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-18 22:18

    See the documentation Laravel 5.7

    A Comment belongTo an unique Post

    class Comment extends Model
    {
        /**
         * Get the post that owns the comment.
         */
        public function post()
        {
            return $this->belongsTo('App\Post');
        }
    }
    

    A Post can Have multiple Comments

    class Post extends Model
    {
        /**
         * Get the comments for the blog post.
         */
        public function comments()
        {
            return $this->hasMany('App\Comment');
        }
    

    When you want to update/delete a belongsTo relationship, you may use the associate/dissociate method.

    $post= App\Post::find(10);
    $comment= App\Comment::find(3);
    $comment->post()->associate($post); //update the model
    
    $comment->save(); //you have to call save() method
    
    //delete operation
    $comment->post()->dissociate(); 
    
    $comment->save(); //save() method
    

提交回复
热议问题