Reputation: 6449
There are two important models Resume
and Skill
. Resume
has many skills through ResumeSkill
.
When I submit my form with skills, before adding them to resume, I remove all the skills it already has.
But I'm having this problem when I run the methods attach()
and detach()
:
Call to undefined method Illuminate\Database\Query\Builder::detach()
This is my Resume model class:
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
class Resume extends BaseModel{
public function skills(){
return $this->hasManyThrough('\myApp\Skill', '\myApp\ResumeSkill');
}
}
And the main script:
$record = \myApp\Resume::find($id);
$record->skills()->detach();
foreach($skills as $skill_id){
$record->skills()->attach($skill_id);
}
What is wrong? Some answers I see say attach()
is a BelongsTo method, but they must be old answers: https://laravel.com/docs/5.2/eloquent-relationships#has-many-through. Anyway, associate/dissociate don't work as well.
@solved
I should have used BelongsToMany
. And attach
/ detach
DOES work with this relationship.
Upvotes: 2
Views: 6984
Reputation: 389
The hasManyThrough is a short-cut for accessing distant relations via an intermediate relation. For Many-to-many relations is define method belongsToMany.
public function skills() {
return $this->belongsToMany('App\Skill', 'ResumeSkill', 'idResume', 'idSkill');
}
Upvotes: 2