Laravel 5.7-数据透视表attach()

时间:2018-12-05 17:05:59

标签: laravel laravel-5 pivot-table

我无法在设置中使用attach()

每个User可以有多个Order,而其中可以有多个Product

User.php

    public function orders()
{
    return $this->hasMany(Order::class);
}

Order.php

    public function users()
{
    return $this->belongsTo(User::class);
}

    public function products()
{
    return $this->belongsToMany(Product::class)
                ->withTimestamps()
                ->withPivot('qty');
}

Product.php

    public function orders()
{
    return $this->belongsToMany(Order::class)
                ->withTimestamps()
                ->withPivot('qty');
}

我有一个create.blade.php,它旨在显示所有可用的产品,每种产品的数量都可以选择,这将保存在数据透视表中。

create.blade.php

{{ Form::open(array('url' => '/orders/store')) }}

@foreach ($products as $product)
    <div>
        <span class="mealname">{{ $product->name }}</span>
        <hr>
        <p>{{ $product->description }}</p>
    </div>

    <div class="qty">
        {{ Form::text( 'qty', 0, [ 'type' => 'tel' ]) }}
    </div>
@endforeach

{{ Form::select('delivery_day', ['M' => 'Monday', 'W' => 'Wednesday'],
    null, ['placeholder' => 'Delivery Day'])
}}
{{ Form::submit('Place Order') }}
{{ Form::close() }}

当我提交请求时,仅保存Order表中的字段,

public function store(Request $request)
{
    // Validate
    $request->validate([
        'qty'=> 'integer',
      ]);

  # Create New Order
    $order = new Order;
    $id = Auth::user()->id;
    $order->user_id = $id;

     // passed in parameters of form (not qty)

    auth()->user()->orders()->save($order); // save order

  # Pivot attach()

    HERE I AM LOST

    return redirect('complete')->with('success', 'Order has been created');
}

我相信这是我试图以一种形式通过多种产品的事实((我相信我在使用attach()的时候应该可以作为一次产品通过。

我尝试了各种解决方案,但仍然无法填充数据透视表。

我最后的尝试是将product_id通过一个隐藏字段,然后运行它。

    $attach_data = [];
    for ($i = 0; $i < count($product_ids); $i++);
    $attach_data[$product_ids[$i]] = ['qty' => $qtys[$i]];

    $order->product_ids()->attach($attach_data);

但是,这没有用。

1 个答案:

答案 0 :(得分:2)

根据文档(https://laravel.com/docs/5.7/eloquent-relationships#updating-many-to-many-relationships),这是附加多个项目的一种方法:

$user->roles()->attach([
  1 => ['expires' => $expires],
  2 => ['expires' => $expires]
]);

所以您必须对此进行修改:

# Create New Order
$order = new Order;
$id = Auth::user()->id;
$order->user_id = $id;
$order->save();

// change this for your array of ids
$products_to_sync_ids = [1,3,23];

$sync_data = [];
$qty = 1; <----- I dont know if you are inserting them with the same qty
for($i = 0; $i < count($products_to_sync_ids); $i++))
   $sync_data[$products_to_sync_ids[$i]] = ['qty' => $qty];

$order->products()->sync($sync_data);

尝试检查产品是否正确插入到数据透视表上,然后修改代码以插入每个带有其数量的代码。