Chron's avatar
Level 6

General error: 1364 Field column_id doesn't have a default value

Is there a way to add an additional value in a sync many to many?

I tried this but I'm getting General error: 1364 Field column_id doesn't have a default value error:

 $foo = Foo::where('name', $request['foo'])->first();

            foreach ($request['bars'] as $k => $bar) {
                $bars[$k] = Bar::firstOrCreate([
                    'name' => $bar
                ]);

                $user->bars()->sync([$bars[$k]->id, ['foo_id' => $foo->id]]);
	}
0 likes
1 reply
guybrush_threepwood's avatar
Level 33

Hi @chron

What about?

$user->bars()->sync([
    $bars[$k]->id => ['foo_id' => $foo->id]
]);

Looking at your code it seems you're attempting to sync a single value inside of the loop. Shouldn't you do it outside the loop? You'll end up with a single record attached if you not.

$foo = Foo::where('name', $request['foo'])->first();
$bars = [];

foreach ($request['bars'] as $k => $bar) {
    $barId = Bar::firstOrCreate(['name' => $bar])->id;
    $bars[$barId] = ['foo_id' => $foo->id]; 
}

$user->bars()->sync($bars);
1 like

Please or to participate in this conversation.