Laravel BelongtoMany关系与两个模型在关系中节省了额外的列

时间:2018-07-22 22:59:17

标签: laravel has-and-belongs-to-many

我尝试构建表单以创建发票,然后生成pdf

我的Db结构

表格:

-发票包含日期| invoice_num | client_id

-文章包含的名称|描述|价格

-article_invoice 包含 invoice_id | article_id | qte *(数量)*

使用“属于多个”关系保存article_id和invoice_id

我的发票管理器

  public function store(Request $request){
      $qte = $request['qte'];

      $request = $request['fields'];

      $facture = Facture::create(['date'=>'2018-08-22', 'facture_num'=>'4','client_id'=>'6']);

      $facture->article()->sync($request);

      $facture->article()->update($qte);

  }

我的观点

<div class="controls">
    {!! Form::open(array('route' =>'factures.store' ,'method'=>'post','enctype'=>'multipart/form-data')) !!}
    <div class="entry input-group col-md-6">
        <select class="form-control" name="fields[]" type="text" placeholder="Type something">
            @foreach($articles as $article)
                <option value="{{$article->id}}">{{ $article->designation}}</option>
            @endforeach
        </select>
        <input type="number" name="qte[]">

        <span class="input-group-btn">
            <button class="btn btn-success btn-add" type="button">
                <span class="glyphicon glyphicon-plus"></span>
            </button>
        </span>
    </div>
    <br>
</div>
</div>

<button type="submit" class="btn btn-primary btn-sm">
        <i class="fa fa-dot-circle-o"></i> Submit
</button>
{!! Form::close() !!}

**在同步article_invoice之后,我想保存qte的任何帮助吗? **

2 个答案:

答案 0 :(得分:0)

您可以传递-> $facture->article()->sync([$request,$extra_columns]);

之类的多余列

答案 1 :(得分:0)

解决方案:

控制器:

 $data = Input::get('qte'); // get input qte ( extra column )
 $fields = Input::get('fields'); // get input ( Ids Of articles )

 $syncData = array();

  for ($i=0;$i<count($fields);$i++){

      $syncData[$fields[$i]] = array('qte' => $data[$i]);

  }

  $facture->article()->sync($syncData);

$ syncData 必须是这样的:

array:3 [▼   
         7 => array:1 [▼                    // " 7 " is article Id
                       "qte" => "4"   ]    //qte is the extra column.
         8 => array:1 [▼
                       "qte" => "10"   ] 
         10 => array:1 [▼
                        "qte" => "250"   ] ]