Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The application has the models:

Atividade.php

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


Intervencao.php

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


The following code works:

Atividade::find($id)->intervencoes()->attach($intervencao_id);

But, this...

Intervencao::find($id)->atividades()->attach($atividade_id);

Returns an BadMethodCallException:

Call to undefined method IlluminateDatabaseQueryBuilder::attach()


SOLUTION (thanks to @gnack):

I was trying to set a many-to-many relationship, so just needed to change this...

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

To this:

return $this->belongsToMany('Atividade');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
903 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...