【问题标题】:Laravel - Saving data to many-to-many relationshipLaravel - 将数据保存到多对多关系
【发布时间】:2014-05-20 10:19:03
【问题描述】:

是否可以将更多数据保存到多对多数据透视表中?

我的代码:

    public function lists() {
        return $this->belongsToMany('ShoppingList','shopping_list_ingredients','shopping_list_id','ingredients_id')
        ->withPivot(array('unit','amount'))
        ->withTimestamps();
}  

反之亦然!
现在,我需要将附加数据添加到数据透视表中。

这是我的保存代码:

    $list = new ShoppingList;
    $list->user_id = Auth::user()->id;
    $list->title = Input::get('recipe_title');
    $list->save();
    $list->ingredients()->sync(Input::get('ingredient'));
    $list->push();  

和我的视图代码:

- {{$i->amount}} {{$i->unit}} {{$i->name}} - {{ Form::checkbox('ingredient[]', $i->id) }}<br/>  

现在我需要以某种方式将每个 ID 的“数量”和“单位”传递到控制器和枢轴中。目前,它只保存 ID。

我该怎么做?

【问题讨论】:

    标签: php laravel pivot relationship eloquent


    【解决方案1】:

    你可以试试这样的:

    $ingredientId = Input::get('ingredient');
    $amount = 'some amount';
    $unit = 'some unit';
    $pivotData = array($ingredientId => array('amount' => $amount, 'unit' => $unit));
    
    $list->ingredients()->sync($pivotData);
    

    您也可以使用attach 方法,阅读Laravel Website 上的文档了解更多信息。

    【讨论】:

      【解决方案2】:

      你必须使用附加功能。

      $list->ingredients()->attach($ingredients->id,['unit' => $unit, 'amount' => $amount]);
      

      【讨论】:

        猜你喜欢
        • 2014-05-31
        • 2018-03-20
        • 1970-01-01
        • 1970-01-01
        • 2018-07-11
        • 2015-03-05
        • 2014-09-02
        • 1970-01-01
        • 2017-07-17
        相关资源
        最近更新 更多