[英]Laravel - error saving record with one to many relationship
努力与laravel关系更新我的代码。
我有两张桌子。 客户和与客户之间具有hasMany关系的预订和与客户之间具有属于关系的预订和预订。
预订表还通过链接表与产品表具有多对多关系。
我获得了客户记录,现在我需要为客户创建一个预订。
我假设过程是:创建预订对象,将预订附加到客户,然后链接到产品。 (预订表有一些关系,但我现在将使其正常工作)
如果我尝试使用此代码,则会收到错误消息, Field 'customer_id' doesn't have a default value
-数据库表允许为null,并且未设置验证规则,因此假设这与我已建立的关系有关。
`$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);`
错误发生在$reservation->save();
然后,我需要使用创建的$ reservation在产品链接表中创建条目,因此需要能够访问新创建的预订及其与产品的关系。
我可以使用$customer->reservation()->save($reservation);
创建条目$customer->reservation()->save($reservation);
但是然后我似乎没有可使用的$ reservation对象(或者我可以吗?)
我对这种关系感到非常困惑,非常感谢所有帮助以了解如何使它起作用
谢谢
这是我在模型中的关系:
Customer Class:
public function reservation() {
return $this->hasMany('Reservation');
}
Reservation Class:
public function customer() {
return $this->belongsTo('Customer');
}
似乎有效的唯一方法是$customer->reservation()->save($reservation);
-因此,我认为这是正确的方法,因此必须重新编写代码。 associate()
更新:在mysql中重新创建了我的表-现在我可以按预期保存原始预订记录,然后使用以下方式将其与客户记录相关联:
$reservation->customer()->associate($customer)
这需要一段时间才能融入我的生活!
第1部分
由于客户有很多预订,因此您需要客户ID才能添加预订。
在您的代码上,
您需要首先获得拥有预订的客户
$customer = Customer::find($id);
现在,
$reservation = new Reservation;
$reservation->customer_id = $customer->id;
$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();
然后, $reservation->save();
现在应该成功。
第2部分
关于您的问题:
“我可以使用$ customer-> reservation()-> save($ reservation)创建条目;但是然后我似乎没有可使用的$ reservation对象(或者我可以吗?)”
您可以通过使用获得客户的所有预订
$reservations = $customer->reservation->get();
//where customer is the one you had on Customer::find($id);
然后,您可以逐个循环预订。 (尽管我认为您可能需要保留ID,所以上面的第一种方法更好)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.