Laravel attach() method not working to hasMany side

前端 未结 4 1464
孤街浪徒
孤街浪徒 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
    
    0 讨论(0)
  • 2020-12-18 22:26

    attach() is for many-to-many relationships. It seems your relationship is supposed to be a many-to-many but you have not set it up correctly for that.

    class Intervencao extends Eloquent {
        public function atividades() {
            return $this->belongsToMany('Atividade');
        }
    }
    

    Then the attach() should work

    0 讨论(0)
  • 2020-12-18 22:32

    See the Laravel documentation here: http://laravel.com/docs/eloquent#inserting-related-models

    Basically you have set up two different types of relationships for the same two tables - you've set up a many-to-many and a one-to-many. It looks as though you probably wanted a many-to-many, so you'll need to change this line:

    return $this->hasMany('Atividade');
    

    To this:

    return $this->belongsToMany('Atividade');
    

    This will set the relationship up as a many-to-many relationship, which will then support the attach() method.

    The attach() method is only for many-to-many, for other relationships there's save() or saveMany() and associate() (see the docs linked above).

    0 讨论(0)
  • 2020-12-18 22:33

    In my case I've two roles() methods that's why it's throwing this error.

    0 讨论(0)
提交回复
热议问题