Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel 4 updateExistingPivot with where clause not working

I have two models:

user and resource

And relation table is resource_user.

the fields in resource_user are:

id | resource_id | user_id | another_id

I have this relation in user:

public function resources() {
        return $this->belongsToMany('Resource')->withPivot(array(
            'value',
            'another_id',
        ));
    }

Now I want update my pivot table:

(in model user there is this code example)

$this->resources()->whereAnotherId(1)->updateExistingPivot($resource_id, array(
                            'value' => $value,
                            'updated_at' => new DateTime,
                        ));

The problem is the another_id.

If I have two entries in my relation table (resource_user) but with different another_id 's. in this example, laravel will update BOTH entries. But this is not what I want. In this example only one entry should be updated (the entry with another_id = 1). Is this a bug, or how can I update my pivot table (the sync() function won't work with my table setup here)..

like image 691
goldlife Avatar asked Mar 20 '15 15:03

goldlife


1 Answers

Try using wherePivot() instead. With whereAnotherId(1) you are targeting the table of Resource and not the pivot table...

$this->resources()->wherePivot('another_id', 1)
                  ->updateExistingPivot($resource_id, array(
                        'value' => $value,
                        'updated_at' => new DateTime,
                    ));
like image 86
lukasgeiter Avatar answered Oct 23 '22 02:10

lukasgeiter