正在努力用拉拉维尔关系更新我的代码。
我有两张桌子。客户和预订与客户
有许多关系,预订与客户有属于关系。预留表还通过链接表与产品表具有多对多关系。
我获取客户记录正常,现在需要为客户创建预留。
我假设这个过程是:创建预留对象,将预留附加到客户,然后链接到产品。(预订表有一些关系,但我现在会让它工作)
如果我尝试此代码,我会收到一个错误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);
创建条目,但是我似乎没有可以使用$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->预订()->save($reservation)创建条目;但是我似乎没有$reservation对象可以使用(或者我?
您可以使用以下命令获取客户的所有预订
$reservations = $customer->reservation->get();
//where customer is the one you had on Customer::find($id);
然后,您可以逐个循环访问预留。(虽然我认为你可能想要预订ID,所以上面的第一种方法更好)