【问题标题】:Laravel - error saving record with one to many relationshipLaravel - 具有一对多关系的错误保存记录
【发布时间】: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


【解决方案1】:

第 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,所以上面的第一种方法更好)

【讨论】:

    猜你喜欢
    • 2017-08-20
    • 1970-01-01
    • 2015-03-05
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    相关资源
    最近更新 更多