加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

php – Laravel attach()方法不适用于hasMany方面

发布时间:2020-12-14 19:46:27 所属栏目:大数据 来源:网络整理
导读:该应用程序有以下模型: Atividade.php class Atividade extends Eloquent { public function intervencoes() { return $this-belongsToMany('Intervencao'); }} Intervencao.php class Intervencao extends Eloquent { public function atividades() { retu
该应用程序有以下模型:

Atividade.php

class Atividade extends Eloquent {
    public function intervencoes() {
        return $this->belongsToMany('Intervencao');
    }
}

Intervencao.php

class Intervencao extends Eloquent {
    public function atividades() {
        return $this->hasMany('Atividade');
    }
}

以下代码有效:

Atividade::find($id)->intervencoes()->attach($intervencao_id);

但是这个…

Intervencao::find($id)->atividades()->attach($atividade_id);

返回BadMethodCallException:

Call to undefined method IlluminateDatabaseQueryBuilder::attach()

解决方案(感谢@gnack):

我试图建立一个多对多的关系,所以只需要改变这个……

return $this->hasMany('Atividade');

对此:

return $this->belongsToMany('Atividade');
请参阅Laravel文档:
http://laravel.com/docs/eloquent#inserting-related-models

基本上,您为相同的两个表设置了两种不同类型的关系 – 您已经设置了多对多和一对多.看起来你可能想要多对多,所以你需要改变这一行:

return $this->hasMany('Atividade');

对此:

return $this->belongsToMany('Atividade');

这将把关系设置为多对多关系,然后支持attach()方法.

attach()方法仅适用于多对多,对于其他关系,还有save()或saveMany()和associate()(请参阅上面链接的文档).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读