Laravel Sync error
Asked Answered
B

1

18

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,

the array looks like this,

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

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()

Baseburner answered 23/10, 2014 at 12:43 Comment(2)
Are you sure you don't have any column in table for Organisation with projects name ?Ululate
There is no column called projects in the organisation tableBaseburner
A
28

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

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

instead of:

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

sync() works only for many to many relationship

Ahola answered 23/10, 2014 at 13:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.