Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
927 views
in Technique[技术] by (71.8m points)

php - Laravel attach() method not working to hasMany side

The application has the models:

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');
    }
}


The following code works:

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

But, this...

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

Returns an BadMethodCallException:

Call to undefined method IlluminateDatabaseQueryBuilder::attach()


SOLUTION (thanks to @gnack):

I was trying to set a many-to-many relationship, so just needed to change this...

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

To this:

return $this->belongsToMany('Atividade');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

See the Laravel documentation here: http://laravel.com/docs/eloquent#inserting-related-models

Basically you have set up two different types of relationships for the same two tables - you've set up a many-to-many and a one-to-many. It looks as though you probably wanted a many-to-many, so you'll need to change this line:

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

To this:

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

This will set the relationship up as a many-to-many relationship, which will then support the attach() method.

The attach() method is only for many-to-many, for other relationships there's save() or saveMany() and associate() (see the docs linked above).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...