Many to Many Relation

how can i custom many to many relationship in filament i have this code class CreateProduct extends CreateRecord { protected static string $resource = ProductResource::class; protected function handleRecordCreation(array $data): Product { return DB::transaction(function () use ($data) { $product = Product::create($data); if (isset($data['units'])) { foreach ($data['units'] as $unitData) { ProductUnit::create([ 'product_id' => $product->id, 'unit_id' => $unitData['unit_id'], 'price' => $product['price'], ]); } } return $product; }); } } class EditProduct extends EditRecord { protected static string $resource = ProductResource::class; protected function getHeaderActions(): array { return [ Actions\DeleteAction::make(), ]; } protected function handleRecordUpdate(Model $record, array $data): Product { Log::info("message"); return DB::transaction(function () use ($record, $data) { $record->update($data); foreach ($data['units'] as $unitData) { ProductUnit::updateOrCreate( [ 'product_id' => $record->id, 'unit_id' => $unitData['unit_id'], 'price' => $unitData['price'] ] ); } $unitIds = array_column($data['units'], 'unit_id'); $record->units()->whereNotIn('unit_id', $unitIds)->detach(); return $record; }); } } when i create and edit product with units i saw this error SQLSTATE[HY000]: General error: 1364 Field 'price' doesn't have a default value how can is solve that
7 Replies
Aya Alghadban
Aya AlghadbanOP6mo ago
i have code ProductResource but it is not sent yet
LeandroFerreira
LeandroFerreira6mo ago
You can use attach, detach and sync.. check the laravel docs https://laravel.com/docs/11.x/eloquent-relationships#updating-many-to-many-relationships
Laravel - The PHP Framework For Web Artisans
Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.
Aya Alghadban
Aya AlghadbanOP6mo ago
i use attach before but error is same
LeandroFerreira
LeandroFerreira6mo ago
the error says that price is null I guess Is it $fillable in the model? Are you sure you are sending this value?
Aya Alghadban
Aya AlghadbanOP6mo ago
yes i put it in ProductUnit Model
Dennis Koch
Dennis Koch6mo ago
@Aya Alghadban This is the third (!) time I tell you: Please use code formatting (as mentioned in #✅┊rules). Also might be a good idea to read https://discord.com/channels/883083792112300104/1167015843020943390
Aya Alghadban
Aya AlghadbanOP6mo ago
this is ProductResource code i use it with previos codes
Want results from more Discord servers?
Add your server