Laravel 同步错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26528387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:19:13  来源:igfitidea点击:

Laravel Sync error

phplaraveleloquentrelationships

提问by Udders

I am running the following code,

我正在运行以下代码,

if( $organisation->save() ) {

        if(isset($members)) {
            $organisation->users()->sync($members);
        }

        if(isset($teams)) {
            $organisation->teams()->sync($teams);
        }

        if(isset($teams)) {
            $organisation->clients()->sync($clients);
        }

        if(isset($projects)) {
            $organisation->projects()->sync($projects);
        }

        $organisation->load('users');
        $organisation->load('teams');
        $organisation->load('clients');
        $organisation->load('projects');

        return Response::make($organisation, 200);

    }

I am am getting the following error when I try and sync $projects,

当我尝试同步时出现以下错误$projects

the array looks like this,

数组看起来像这样,

[0] => 6so a very very simple array. My relationships in the models look like this,

[0] => 6所以一个非常非常简单的数组。我在模型中的关系看起来像这样,

Organisation

组织

public function projects()
{
    return $this->hasMany('Project');
}

Projects

项目

public function organisations()
{
    return $this->belongsToMany('Organisation', 'organisation_id');
}

As you can see I an organisation can have many projects. I cannot see a reason why I would be getting the following error,

如您所见,一个组织可以有许多项目。我看不出出现以下错误的原因,

Call to undefined method Illuminate\Database\Query\Builder::sync()

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

回答by Marcin Nabia?ek

As it's many-to many relationship in both functions you need to use belongsToMany, so you should use:

由于您需要使用这两个函数中的多对多关系belongsToMany,因此您应该使用:

public function projects()
{
    return $this->belongsToMany('Project');
}

instead of:

代替:

public function projects()
{
    return $this->hasMany('Project');
} 

sync()works only for many to many relationship

sync()仅适用于多对多关系