5

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

goldlife
  • 1,949
  • 3
  • 29
  • 48

1 Answers1

8

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,
                    ));
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • @lukasgeiter, Seems you can help me. Look at this : https://stackoverflow.com/questions/44519339/how-can-i-update-pivot-table-on-laravel – moses toh Jun 13 '17 at 10:52
  • This does not seem to make sense. To use 'where' clause with 'updateExistingPivot' is not very useful. Because 'updateExistingPivot' cannot update multiple M:M relations at once. It can only update a single relation whose id is the first argument of this method. $resource_id = $this->resources()->wherePivot('another_id', 1)->first(); $this->resources()->updateExistingPivot($resource_id, array( 'value' => $value, 'updated_at' => new DateTime, )); – Jasmeet Singh Feb 22 '19 at 12:19