2016-08-03 109 views
1

有两个重要的模型ResumeSkillResume通过ResumeSkill有很多技能。Laravel调用未定义方法Illuminate Database Query Builder :: detach/attach()for hasManyThrough relationships

当我将技能提交给我的表单时,在将它们添加到继续之前,我删除了它已有的所有技能。

但是当我运行的方法attach()detach()我有这样的问题:

调用未定义的方法照亮\数据库\查询\生成器::分离()

这是我的简历模型类:

use Illuminate\Database\Eloquent\SoftDeletes; 
use Illuminate\Database\Eloquent\Model; 

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

和主脚本:

$record = \myApp\Resume::find($id); 
$record->skills()->detach(); 
foreach($skills as $skill_id){ 
    $record->skills()->attach($skill_id); 
} 

出了什么问题?我看到的一些答案attach()是一个属于方法,但它们必须是旧的答案:https://laravel.com/docs/5.2/eloquent-relationships#has-many-through。无论如何,关联/解离都不行。

@solved

我应该用BelongsToMany。并且attach/detachDOES与这种关系一起工作。

回答

2

hasManyThrough是通过中间关系访问远程关系的捷径。对于多对多关系是定义方法belongsToMany。

public function skills() { 
    return $this->belongsToMany('App\Skill', 'ResumeSkill', 'idResume', 'idSkill'); 
} 
+0

但有一个中间表。什么是遥远的关系? –

+0

在我们有三个表格的情况下,例如国家,用户和评论,我想获得特定国家的所有评论。在国家模式将使用此实现:public function comments(){return $ this-> hasManyThrough('App \ Comment','App \ User'); } –

相关问题