【问题标题】:Laravel 5.7 - Pivot table attach()Laravel 5.7 - 数据透视表附加()
【发布时间】:2018-12-05 17:05:59
【问题描述】:

我无法让attach() 在我的设置中工作。

每个User 可以有多个Orders,而Products 可以有多个Products。

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

但是,这不起作用。

【问题讨论】:

  • 您如何尝试使用attach()?您可以将代码添加到您的问题中吗?

标签: laravel laravel-5 pivot-table


【解决方案1】:

根据文档 (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);

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

【讨论】:

  • 我出奇地接近,希望这对其他人有所帮助。
猜你喜欢
  • 2019-07-25
  • 1970-01-01
  • 1970-01-01
  • 2019-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-09
相关资源
最近更新 更多