mercredi 10 juillet 2019

Laravel, sync data with Pivot

Laravel 5.3, I have this 2 models:

User:

public function newFunctions()
{
    return $this
        ->belongsToMany('App\NewFunctions', 'user_newfunctions')
        ->withPivot(['function_count', 'days_count']);
}

NewFunctions:

public function users()
{
    return $this
        ->belongsToMany('App\User', 'user_newfunctions', 'new_function_id', 'user_id')
        ->withPivot(['function_count', 'days_count']);
}

I now how can I save new data to User, with this:

$user = User::findOrFail($id);
$user->name = $request->input('name');
$user->save();

But now I have to update some values of a pivot table. the pivot table is this:

user_id | new_functions_id | function_count | days_count
---------------------------------------------------------
    814 |           1      |   5            |2019-07-19 12:26:19
    814 |           3      |   7            |2019-07-19 12:26:19

I have more than 1 row per user_id. I was trying to use:

$user
    ->newFunctions()
    ->sync([
        'days_count' => $test_date,
        'function_count' => $test_int_number
    ]);

But I'm getting error like:

Ilegal offset type

because is trying to update with this:

array(
    'records' => array(
        'days_count' => object(Carbon), 'function_count' => '66'),
        'results' => array(),
        'id' => object(Carbon),
        'attributes' => array()

    )
)

in BelongsToMany.php

So:

  • How could I update the values for each user_id on the pivot table?
  • And how should use syncto update just 'function_count' and 'days_count'? they come from request.


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire