dimanche 16 juin 2019

updateExistingPivot Laravel 5.8

I'm unable to get the updateExistingPivot function to work properly. I also am having a hard time to see the produced query generated by this function in order to debug it.

My Test model;

class Test extends Model
{
...
    public function users(){
        return $this->belongsToMany(User::class)->withPivot('grade')->withTimestamps();
    }
}

My User model;

class User extends Authenticatable
{
...
    public function tests(){
        return $this->belongsToMany(Test::class)->withPivot('grade');
    }
}

Say I have an array of the following objects as request data;

[
     {
     "user_id":11,
     "grade":5.0,
     "test_id":5
     },
     ...
]

All the data in these objects exist in the pivot table, and I would like to update the grade using the user and test id keys. I currently have the following query that loops through all the request objects:

    $test = $this->show($testId);
    foreach($request->post() as $requestData)
    {
        $user_id = $requestData['user_id'];
        $grade = $requestData['grade'];
        $updateQuery = $test->users()->updateExistingPivot($user_id, ['grade' => $grade]);
    }

When I lookup the fields in my database I see the updated_at being updated when I execute this code. However, the grade fields do not get updated..

The pivot table looks like the following:

+------------+---------------------+------+-----+---------+----------------+
| Field      | Type                | Null | Key | Default | Extra          |
+------------+---------------------+------+-----+---------+----------------+
| id         | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| test_id    | bigint(20) unsigned | NO   | MUL | NULL    |                |
| user_id    | bigint(20) unsigned | NO   | MUL | NULL    |                |
| grade      | double(2,1)         | NO   |     | NULL    |                |
| created_at | timestamp           | YES  |     | NULL    |                |
| updated_at | timestamp           | YES  |     | NULL    |                |
+------------+---------------------+------+-----+---------+----------------+

Doing something along the lines of this also hasn't worked;

    foreach($request->post() as $requestData)
    {
        $user_id = $requestData['user_id'];
        $grade = $requestData['grade'];

        $query = $test->users()
        ->wherePivot('user_id', '=', $user_id)->first()->pivot;
        $query->grade = $grade;
        $query->save();
    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire