Laravel attach() method not working to hasMany side
laravel-4, php
Solution
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).
Problem
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 Illuminate\Database\Query\Builder::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'); ```