Laravel - error saving record with one to many relationship
Struggling to update my code with laravel relationships.
I have two tables. Customer and Reservations with Customer having a
hasMany relationship with Reservation and Reservation having a belongs to
relationship with Customer.
The reservation table also has a many to many relationship with a product
table via a link table.
I obtain the customer record ok and I now need to create a reservation for
the customer.
I'm assuming the process is: create the reservation object, attach the
reservation to the customer and then link to the product. (the reservation
table has a few relationships but I'll get this working for now)
If I try this code I get an error Field 'customer_id' doesn't have a
default value - the database table allows null and there are no validation
rules set so assume this is to do with the relationship I've set up.
`$reservation = new Reservation;
$reservation->play_date=$play_date->format('Y-m-d');
$reservation->booked_date=$booked_date->format('Y-m-d');
$reservation->am_tee=$am_time->format('H:i:s');
$reservation->pm_tee=$pm_time->format('H:i:s');
$reservation->save();
$customer->reservation()->associate($reservation);`
The error occurs with $reservation->save();
I then need to use the created $reservation to create entries in the
product link table so need to be able to access the newly created
reservation and it's relationship with products.
I can create the entry using $customer->reservation()->save($reservation);
but then I don't seem to have a $reservation object to work with (or do
I?)
I'm very confused by the relationships so grateful for all help to
understand how to get this to work
Thanks
No comments:
Post a Comment