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?
It seems that you have defined the intermediate table with fields (at least the usu_insert field) that cannot be NULL.
That is what the SQL error tells you, that you do not have a default value for the usu_insert field in the user_supplier table
You have 2 options:
1 - If those fields can be NULL define them as NULL, for example, in the migration:
2 - If the fields must have a value (they cannot be NULL), pass them in the seeder, for example:
This without seeing the definitions of the fields in the migration or knowing what you need in those fields of the intermediate table ;-)