I am trying to create a Seeder in Laravel 8, I have defined a BelongsToMany relationship to create a pivot table between a USERS and PROVIDERS table, the relationships are defined as follows;
// Modelo USER
public function proveedor(): BelongsToMany
{
return $this->belongsToMany(Proveedores::class, 'usuario_proveedor', 'id_usuario', 'id_proveedor')
->using(UsuarioProveedor::class)
->withPivot('usu_insercion', 'usu_modificacion', 'usu_eliminacion')
->withTimestamps();
}
// Modelo PROVEEDORES
public function usuarios()
{
return $this->belongsToMany(User::class, 'usuario_proveedor', 'id_proveedor', 'id_usuario')
->using(UsuarioProveedor::class)
->withPivot('usu_insercion', 'usu_modificacion', 'usu_eliminacion')
->withTimestamps();
}
I use the USING methods to indicate the model of the PIVOT table, I do this because I have a TRAIT that inserts data for auditing, which are the fields defined in the withPivot method.
The issue is that in the controller, the portion that associates this data works perfectly;
// carga la relacion con el proveedor si corresponde
if ($request->tip_usuario === 'P') {
$usuario->proveedor()->attach($request->proveedor);
}
My problem is when I try to upload this data with Faker, in a Seeder, or when I try to associate a user with a provider from Tinker, I get the following message;
//Tinker
$user->provider()->attach(3) Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1364 Field 'usu_insercion' doesn't have a default value (SQL: insert into
usuario_proveedor
(id_proveedor
,id_usuario
,created_at
,updated_at
) values (3, 62, 2022-02-08 00:37:16, 2022-02-08 00:37:16))'
Seeder code is;
User::factory()->count(5)->create()->each(function ($user) {
$user->proveedor()->attach(rand(1, 11));
});
The error is the following;
Seeding: Database\Seeders\UsersSeeder
Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 1364 Field 'usu_insercion' doesn't have a default value (SQL: insert into `usuario_proveedor` (`id_proveedor`, `id_usuario`, `created_at`, `updated_at`) values (6, 7, 2022-02-08 00:47:08, 2022-02-08 00:47:08))
Does anyone have any idea what could be the problem?