首页 文章

Laravel 5.7 - 数据透视表附件()

提问于
浏览
1

我无法在我的设置中使用 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() 时作为arry传递 .

我尝试了各种解决方案,但我仍然无法获得数据透视表 .

我的最后一次尝试是通过隐藏字段传递 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 回答

  • 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);
    

    尝试检查产品是否正确插入数据透视表,然后修改代码以插入每个代码及其数量 .

相关问题