Laravel保存了hasAndBelongsToMany关系

时间:2014-03-09 18:00:43

标签: php laravel laravel-4

在我的Laravel 4应用程序中,我有模型:

  • 付款(id,payment_date,收件人)
  • PayerPayment (id,payment_id,payer_id,amount_paid,included_in_payment)
  • 付款人(身份证,姓名)

您可能已经注意到,付款可能有很多付款人,付款人可以付多少钱。这些模型由PayerPayment模型加入,该模型还包含其他字段(amount_paid,included_in_payment),其中显示每个付款人支付的金额以及是否应将其包含在整体付款中。

当我添加新付款时,我希望表单包含每个付款人的输入,我可以填写2 PayerPayment 字段(amount_paid,included_in_payment)。

我现在这样做的方法是将一组记录的付款人传递给构建表格的视图:

控制器:

public function add()
{
    $payers = Payer::all();
    return View::make('payments.add')->with('payers', $payers);
}

查看:

  {{ Form::open( array('route'=>'payments.store', 'class'=>'form-signup')) }}

  {{ Form::input('date', 'payment_date', null, array('class'=>'form-control')) }}
  {{ Form::text('recipient', null, array('class'=>'form-control')) }}

  @foreach ($payers as $payer)
      <fieldset>
      {{ Form::label($payer->id . '-amount', $payer->name) }} <br>
      {{ Form::input('number', $payer->id . '-amount_paid', null, array('class'=>'form-control', 'step' => 'any', 'value' => 0)) }}
      {{ Form::checkbox($payer->id . '-included_in_payment', null, array('class'=>'form-control', 'label'=>'pays')) }}
      {{ Form::label($payer->id . '-included_in_payment', 'pays') }}
     </fieldset>
  @endforeach

  {{ Form::submit('Add Payment', array('class'=>'btn btn-primary')) }} 

  {{ Form::close() }}

现在,当我来保存付款时,我的控制器目前看起来像这样:

$payment = new Payment;
            $payment->payment_date = Input::get('payment_date');
            $payment->recipient = Input::get('recipient');
            $payment->save();

            //Save the amount each payer paid
            $payers = Payer::all();
            foreach ($payers as $payer){
                $payment_payer = new PayerPayment;
                $payment_payer->payment_id = $payment->id;
                $payment_payer->payer_id = $payer->id;

                $payment_payer->amount_paid = Input::get($payer->id . '-amount-paid') ? Input::get($payer->id . '-amount_paid') : 0;

                $payment_payer->included_in_payment = Input::has($payer->id . '-included_in_payment');
                $payment_payer->save();
            }

这似乎是一种糟糕的做事方式。我通过循环遍历所有付款人,将新的PayerPayment与父付款的保存分开。 laravel是否有办法一次性实现这一目标?

1 个答案:

答案 0 :(得分:1)

你所追求的是“inserting related models

因此,在您保存付款后,您可以将其添加到用户:

...
$payment->save();

$payers = Payer::all();
foreach ($payers as $payer){

    $extra_details = array(
        'amount_paid' => Input::get($payer->id . '-amount-paid') ? Input::get($payer->id . '-amount_paid') : 0, 
        'included_in_payment' = Input::has($payer->id . '-included_in_payment')
    );

    $payer->payments()->attach($payment->id, $extra_details);

}