【问题标题】:Laravel Call to undefined method Illuminate\Database\Query\Builder::detach/attach() for hasManyThrough relationshipsLaravel 调用未定义的方法 Illuminate\Database\Query\Builder::detach/attach() 以获得 hasManyThrough 关系
【发布时间】:2016-12-09 17:52:12
【问题描述】:

有两个重要的模型Resume 和Skill。 Resume通过ResumeSkill拥有很多技能。

当我提交包含技能的表单时,在将它们添加到简历之前,我会删除它已经拥有的所有技能。

但是当我运行 attach() 和 detach() 方法时遇到了这个问题:

调用未定义的方法 Illuminate\Database\Query\Builder::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() 是 BelongsTo 方法,但它们必须是旧答案:https://laravel.com/docs/5.2/eloquent-relationships#has-many-through。无论如何,关联/分离也不行。

@solved

我应该使用BelongsToMany。 attach / detach 确实可以处理这种关系。

【问题讨论】:

    标签: php laravel eloquent laravel-5.2


    【解决方案1】:

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

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

    【讨论】:

    • 但是有一个中间表。什么是远亲?
    • 如果我们有三个表,例如国家、用户和 cmets,我想获取特定国家的所有 cmets。在 Country 模型中将使用此实现: public function cmets() { return $this->hasManyThrough('App\Comment', 'App\User'); }
    猜你喜欢
    • 2014-04-25
    • 1970-01-01
    • 2018-12-10
    • 2017-03-31
    • 2018-10-03
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    相关资源
    最近更新 更多