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

Ble*_*son 10 php laravel-4

该应用程序有以下模型:

Atividade.php

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


Intervencao.php

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


以下代码有效:

Atividade::find($id)->intervencoes()->attach($intervencao_id);
Run Code Online (Sandbox Code Playgroud)

但是这个...

Intervencao::find($id)->atividades()->attach($atividade_id);
Run Code Online (Sandbox Code Playgroud)

返回BadMethodCallException:

调用未定义的方法Illuminate\Database\Query\Builder :: attach()


解决方案(感谢@gnack):

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

return $this->hasMany('Atividade');
Run Code Online (Sandbox Code Playgroud)

对此:

return $this->belongsToMany('Atividade');
Run Code Online (Sandbox Code Playgroud)

Nic*_*oad 24

请参阅Laravel文档:http://laravel.com/docs/eloquent#inserting-related-models

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

return $this->hasMany('Atividade');
Run Code Online (Sandbox Code Playgroud)

对此:

return $this->belongsToMany('Atividade');
Run Code Online (Sandbox Code Playgroud)

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

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


Use*_*356 5

请参阅文档 Laravel 5.7

评论属于一个独特的帖子

class Comment extends Model
{
    /**
     * Get the post that owns the comment.
     */
    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}
Run Code Online (Sandbox Code Playgroud)

一个帖子可以有多个评论

class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
Run Code Online (Sandbox Code Playgroud)

当你想要更新/删除一个belongsTo关系时,你可以使用associate/dissociate方法。

$post= App\Post::find(10);
$comment= App\Comment::find(3);
$comment->post()->associate($post); //update the model

$comment->save(); //you have to call save() method

//delete operation
$comment->post()->dissociate(); 

$comment->save(); //save() method
Run Code Online (Sandbox Code Playgroud)