2016-08-03 111 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'); } –

相關問題