【发布时间】:2013-09-19 09:14:26
【问题描述】:
努力用 laravel 关系更新我的代码。
我有两张桌子。 Customer 和 Reservations 与 Customer 具有 hasMany 关系,Reservation 和 Reservation 与 Customer 具有归属关系。
预订表也通过链接表与产品表建立多对多关系。
我获得了客户记录,我现在需要为客户创建预订。
我假设过程是: 创建预订对象,将预订附加到客户,然后链接到产品。 (预订表有一些关系,但我现在就让它工作)
如果我尝试此代码,我会收到错误 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)
这需要一段时间才能融入我!
【问题讨论】:
-
我不确定我是否理解
$customer->reservation()->save($reservation);与$customer->reservation()->associate($reservation);的行为方式有何不同,从而产生了问题?您能否展示在 Customer 和 Reservation 模型中创建的关系方法? -
你在哪里定义
$customer? -
$customer 在前面的代码中定义为 Customer::find($id);
标签: php laravel laravel-4 eloquent