Victor Ferreira Victor Ferreira - 6 months ago 164
PHP Question

Laravel Call to undefined method Illuminate\Database\Query\Builder::detach/attach() for hasManyThrough relationships

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
and
detach
does work with this king of relationship.

Answer

As I cannot comment right now since my reputation is low. I've to post this as answer. I am curious to know that did you somehow named the foreign keys as per your convenient. I am asking this because I don't see anything wrong in whatever you've posted. So You and I need to make sure that the issue is not in defining the relationship. You did not define any foreign key name here which you need to in case the foreign keys are renamed

public function skills(){
    return $this->hasManyThrough('\myApp\Skill', '\myApp\ResumeSkill');
}

If you did rename it then I guess you know what to do

public function skills(){
    return $this->hasManyThrough('\myApp\Skill', '\myApp\ResumeSkill','fk_intermediate_table','fk_finaltable');
}

UPDATE

For hasManyThrough relationship to work with your case, You must need resumes table to refer resume_skills which in turn refer to skills table. Here resume_skills is Intermediate Table.

Your resume_skills is pivot table that refers both resumes & skills table. You should use belongsToMany relationship in your case. And as per Laravel Official Doc attach() & detach() methods only works with belongsToMany relationship.