Hardist
Hardist

Reputation: 1983

Laravel working with belongsToMany and extra fields

I am trying to save a simple belongsToMany relation into my database. First, my table:

    Schema::create('user_activity_log', function (Blueprint $table) {
        $table->unsignedBigInteger('activity_id');
        $table->unsignedBigInteger('log_id');
        $table->unsignedInteger('sets');
        $table->unsignedInteger('reps');
        $table->primary(['activity_id', 'log_id']);

        $table->foreign('activity_id')->references('id')->on('user_activities')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->foreign('log_id')->references('id')->on('user_logs')
            ->onDelete('cascade')
            ->onUpdate('cascade');
    });

My Log and Activity models have these relations:

Log:

public function activities()
{
    return $this->belongsToMany(Activity::class, 'user_activity_log', 'log_id', 'activity_id')->withPivot(['sets', 'reps']);
}

Activity:

public function logs()
{
    return $this->belongsToMany(Log::class, 'user_activity_log', 'activity_id', 'log_id')->withPivot(['sets', 'reps']);
}

And in both models I am using:

protected $guarded = [];

When adding a new activity to an existing log, in my store method I am doing simply this:

$log->activities()->syncWithoutDetaching([$request->input('activity_id'), ['sets' => $request->input('sets'), 'reps' => $request->input('reps')]]);

I am getting this error:

SQLSTATE[HY000]: General error: 1364 Field 'sets' doesn't have a default value 

insert into `user_activity_log` (`activity_id`, `log_id`) values (3, 2)

I cannot figure out why it is not saving the sets and reps. When I dd() the $request values, they are there. And my $log is also there.

Upvotes: 1

Views: 36

Answers (1)

AmooAti
AmooAti

Reputation: 1130

You have an issue in calling syncWithoutDetaching.

Your data must be an associative array where the keys are the IDs and values are data.

In your code, you used an indexed array instead of an associative array, where the first index is id and the second index is data, but it must be an associative array where the key is activity_id, and the value of that key must be an associative array containing sets and reps.

$log->activities()->syncWithoutDetaching([
    $request->input('activity_id') => [
        'sets' => $request->input('sets'),
        'reps' => $request->input('reps')
    ]
]);

Upvotes: 1

Related Questions